Get first non-repeating character in a string

How do you get first non-repeating character in a string.

In Windows PowerShell v5.1 you could use Group-Object but as I showed last time that approach has been taken away in PowerShell v6.1.

Instead you need to loop through the characters in the string and count them

function get-firstnonrepeatcharacter {
   param (

  $a = [ordered]@{}

  $teststring.ToLower().ToCharArray() |
   foreach {
     if ($a.$psitem) {
       $a.$psitem += 1
     else {
       $a += @{$psitem = 1}


  $a.GetEnumerator() | where Value -eq 1 | select -First 1


Input the test string through a parameter. Create an ORDERED hash table for the results – you need to preserve the order in which characters are counted!

Convert the string to lowercase (remove this step if your worried about case) and convert to an array of chars. Pipe into foreach-object. Test is the character is already in the hashtable. If it is increment the count. If it isn’t add it.

Use the getEnumerator() method to access the hash table. use where-object to filter for characters only appearing once. Select the first one.

$ts = ‘lcoauywfnqumfheolfzaliigngulxqdbnzprnylfqvsxathrqsyjowm’

PS> get-firstnonrepeatcharacter -teststring $ts 

Name Value
—-      —–
c          1

This entry was posted in Powershell. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s