0

I have a PowerShell script that fails if only 1 string is fed to an array because it splits it into characters when using Get-Unique and/or Sort-Object. However, if multiple values are provided then it works as expected. So for example:

Expected behavior:

PS X:\> $t = @("asd","bcd") | Get-Unique
PS X:\> $t[0]
asd
PS X:\> $t[1]
bcd

Unexpected (with 1 value):

PS X:\> $t = @("asd") | Get-Unique
PS X:\> $t[0]
a
PS X:\> $t[1]
s
PS X:\> $t[2]
d

Could someone explain why this is happening and how to prevent it? I'd appreciate any input as my searches did not bring any luck.

Thanks

  • `Get-Unique` simply outputs the string `"asd"` - _you_ then split it by indexing into it with `[]` :) use `$t = @( "asd" |Get-Unique )` – Mathias R. Jessen Oct 18 '21 at 13:33
  • Classic PowerSehell gotcha `4a`: [single item collections](https://stackoverflow.com/a/69617202/1701026) – iRon Oct 18 '21 at 13:45
  • Does this answer your question? [Pipe complete array-objects instead of array items one at a time?](https://stackoverflow.com/questions/29973212/pipe-complete-array-objects-instead-of-array-items-one-at-a-time) – iRon Oct 18 '21 at 13:51
  • you can do: `,@("asd")`. – Abraham Zinala Oct 18 '21 at 14:32

1 Answers1

0

Get-Unique doesn't split anything - it just returns the one string value as is, and as a result, $t now contains a scalar string, not an array:

PS ~> $t = "asd" |Get-Unique
PS ~> $t.GetType().FullName
System.String
PS ~> $t
asd

But as soon as you try to access the string value with the index accessor [], it returns the individual [char] value found at the given index.

If you want to ensure the output from Get-Unique (or Sort-Object or any other command that might return 0, 1, or more objects as output), wrap the pipeline in the array subexpression operator @():

PS ~> $t = @( "asd" | Get-Unique )
PS ~> $t[0]
asd
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206