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

4
  • Get-Unique simply outputs the string "asd" - you then split it by indexing into it with [] :) use $t = @( "asd" |Get-Unique ) Commented Oct 18, 2021 at 13:33
  • Classic PowerSehell gotcha 4a: single item collections Commented Oct 18, 2021 at 13:45
  • Does this answer your question? Pipe complete array-objects instead of array items one at a time? Commented Oct 18, 2021 at 13:51
  • you can do: ,@("asd"). Commented Oct 18, 2021 at 14:32

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.