PowerShell – filtering for unique values

powershellpowershell-2.0

I have an input CSV file with a column containing information similar to the sample below:

805265
995874
805674
984654
332574
339852

I'd like to extract unique values into a array based on the leading two characters, so using the above sample my result would be:

80, 99, 98, 33

How might I achieve this using PowerShell?

Best Solution

Use Select-Object and parameter -unique:

$values =
'805265',
'995874',
'805674',
'984654',
'332574',
'339852'

$values |
  Foreach-Object { $_.Substring(0,2) } |
  Select-Object -unique

If conversion to int is needed, then just cast it to [int]:

$ints =
  $values |
  Foreach-Object { [int]$_.Substring(0,2) } |
  Select-Object -unique