A PowerShell mystery by Mark Wojciechowicz
I met with an unexpected behavior in PowerShell’s count function. In SSIS, we needed to check if the contents of a folder were empty before running a process on the contents. The reason being, if the folder was empty, the process would throw an error. So very simply, we hooked up PowerShell to an execute process task, set the working directory to the location that we wanted to check the contents for and then mapped the StandardOutputVariable to capture the result (shown below). In the argument we put the following command:
(Get-Childitem).count -as [int]
Get-Childitem is PowerShell’s cmdlet for getting the contents of a parent item. Wrap that in a count and we have the number of files in the folder. Lastly, we convert that to an integer value.
Since this operation was generally operating on 5 to 10 files at a time or none at all, everything ran as expected. However, I tried reprocessing a single file the other day, only to find that PowerShell returned “0” for the count. After adding more files, I found that it suddenly started returning the correct count again. It seems the function above cannot count items when there is only one. After Googling around for a while, I found that if the Get-Childitem collection is converted to an array, PowerShell can return the correct count for a single item. This is done by adding an “@” sign to the beginning of the statement:
@(Get-Childitem).count -as [int]
Easy as 0, 2 ,3!