PowerShell for Windows Admins

Dec 29 2018   3:58PM GMT

Get first non-repeating character in a string

Richard Siddaway Richard Siddaway Profile: Richard Siddaway


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


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.

 Comment on this Post

There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to:

Share this item with your network: