Wednesday, February 20, 2013

Get-ChildItem returning scalars... revisited


A while back I wrote about this:

Get-ChildItem returns a scalar


Get-ChildItem of course gets the contents of a specified directory and returns a .NET object with various methods and properties. One surprising result reveals itself when you want to use this Powershell cmdlet to discover the number of items in a folder. If there is only one item in the folder, the cmdlet will return a scalar instead of an array. I'll explain with three examples:

Example 1: The folder is empty.

$test = (Get-ChildItem c:\temp).Count

$test will be NULL

Example 2: The folder has one item

$test = (Get-ChildItem c:\temp).Count

$test will be NULL

Example 3: The folder has two items

$test = (Get-ChildItem c:\temp).Count

$test will equal 2

Example 2 reveals this issue and was a surprise to me. The solution is to cast the result to the array you expected it to contain in the first place.

$test = @(Get-ChildItem c:\temp).Count

$test will now always contain the correct value.
 
UPDATE:
This behavior is now fixed in PowerShell 3.0. Not only will

(Get-ChildItem c:\temp).Count

now return "1" when there is one item, but it also now returns "0" when there are no items. a NULL is never returned.
 


Cheers!

No comments:

Post a Comment