Skip to content

Powershell 3.0 arrays of length zero or one

05/04/2013

Here’s something I noticed today about zero or one length arrays:

PS C:\Users\dan> # in a powershell 2.0 console
PS C:\Users\dan> (1).count
PS C:\Users\dan> ($null).count
PS C:\Users\dan> (1,2).count
2
PS C:\Users\dan> @(1).count
1
PS C:\Users\dan> @().count
0

So a single object doesn’t have a count defined (nor does it have a length). If you explicitly define it as an array then it does have count 1 (or 0). This is annoying since if you get a result set of length 1 (or 0) then your code must deal with it differently.

But, in Powershell 3.0:

PS C:\Users\dan> # in a powershell 3.0 console
PS C:\Users\dan> (1).count
1
PS C:\Users\dan> ($null).count
0

That’s a really useful change. The about_Arrays page has a little more info. It’s worth noting that existing scripts written in PS2 will behave differently if they are run on a PS3 host.

Advertisements

From → Powershell

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: