3

#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]
1

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

PS> $foo[0]
1
Filed in: Columns, Tips and Tricks Tags: , , ,

3 Responses to "#PSTip Index into scalar in PowerShell 3.0"

  1. Carlos Lopez says:

    Don’t forget the “@()” operator. 🙂

Leave a Reply

Submit Comment

© 2016 PowerShell Magazine. All rights reserved. XHTML / CSS Valid.
Proudly designed by Theme Junkie.
%d bloggers like this: