Wednesday, October 15, 2014

PowerShell Oddities, Take 4

I ran into another PowerShell oddity today. This one wasted a lot of time. It boils down to the fact that you can index anything. If you use [0] on something that is not a collection, it will return itself. If you use anything else, it will return nothing. Again, this was buried deep in a nested code that was called from functions and it took a long time to figure out what was going on.

Take the following:

$settings = @{"Env1" = "VarValue1"; "Env2" = "VarValue2" }
Write-Output "Count: $($settings.Values.Count)"
Write-Output "Value 0: '$($settings.Values[0])'"
Write-Output "Value 1: '$($settings.Values[1])'"

It sure looks like you are getting a proper collection. Values, is indeed a collection, which makes this result all the more confusing:

Count: 2
Value 0 : 'VarValue2 VarValue1'
Value 1 : ''

Solution:

$values = $setting.Value.Values -as [string[]]
Write-Output "Count: $($values.Count)"
Write-Output "Value 0: '$($values[0])'"
Write-Output "Value 1: '$($values[1])'"

Output:

Count: 2
Value 0 : 'VarValue2'
Value 1 : 'VarValue1'

The weird thing is that I swear I tried doing an implicit cast before I posted my question to http://stackoverflow.com

After posting my question I realized I had not tried an explicit cast. So, I tried that and it worked. That seemed weird, so I tried the implicit cast again and it also worked. I guess I am going crazy. For reference here is the implicit cast:

[string[]]$values = $setting.Value.Values

No comments:

Post a Comment