Powershell 3.0 arrays of length zero or one
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.
Leave a Comment