Making Names Unique

Share |

Join PowerShell.com!
Subscribe to Feed

PowerShell eBook
Sign up for
Your PowerTip of the Day:

Award-winning PowerShellPlus


Admin Guide to PowerShell Remoting


Mastering PowerShell eBook

To make a list of items or names unique, you could use grouping and then, when a group has more than one item, append a numbered suffix to these items. Here's a simple example:

function Convert-Unique($list) {
    $list | Group-Object |
        ForEach-Object {
            $_.Group | 
                ForEach-Object { $i=0 } { 
                    $i++
                    if ($i -gt 1) { $_ += $i }
                    $_
                }
        }
  }

PS> $names = "Peter", "Mary", "Peter", "Fred", "Tom", "Peter"

PS> Convert-Unique $names
Peter
Peter2
Peter3
Mary
Fred
Tom

Of course this is just a very simple algorithm. It assumes that there are no names in the initial list that end with numbers.

Twitter This Tip! ReTweet this Tip!


Posted Apr 09 2012, 06:00 AM by ps1
Copyright 2012 PowerShell.com. All rights reserved.