#PSTip Index into scalar in PowerShell 3.0

Note: This tip requires PowerShell 3.0 or above.

When you assign the output of a command to a variable, you can’t know in advance how many objects are in the variable. It may contain one object (scalar) or an array (collection) of objects. In versions prior to PowerShell 3.0, if you treat a variable as a collection of objects and try to get the first item when the variable contains a single object, you’ll get the following error:

PS> $foo = 1
PS> $foo[0]

Unable to index into an object of type System.Int32.

In PowerShell 2.0, the workaround used to avoid that error was to force the result to an array:

PS> [array]$foo=1
PS> $foo[0]

In PowerShell 3.0, we can now index into scalars without the need to tweak the object:

PS> $foo[0]

About the author: Shay Levy

Shay Levy is a Co-founder and editor of the PowerShell Magazine. He is a multiple-year recipient of the Microsoft MVP award, and a Microsoft Certified Trainer (MCT). Shay often covers PowerShell related topics on his blog and you can also follow him on Twitter at @ShayLevy

Related Posts

%d bloggers like this: