Sunday, August 28, 2011

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.

Cheers!


No comments:

Post a Comment