Making Names Unique

by Apr 9, 2012

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!