Why does Powershell silently convert a string array with one item to a string
Evidently, PowerShell implicitly 'unboxes' a single-item array to a single object,
And zero item results to $null
.
How can I prevent this from happening?
You can't.
How do you deal with this?
Use the array constructor (@(...)
) to force a collection (possibly with zero or one elements) return:
$res = @(ls | %{$_.Name} | ?{$_.Contains("Prog")})
Note the difference between these two results:
PS C:\> ConvertTo-Json -InputObject @(1)
[
1
]
PS C:\> @(1)|ConvertTo-Json
1
PS C:\>
The point is that the 'unboxing' is being done by the pipe operation. ConvertTo-Json still sees the object as an array if we use InputObject rather than piping.
This has been resolved in PowerShell v3:
http://blogs.microsoft.co.il/blogs/scriptfanatic/archive/2012/03/19/Counting-objects-in-PowerShell-3.0.aspx
On a side note, you can find if a name contains something using a wildcard:
PS> ls *og*