Tuesday, September 20, 2011

Powershell Get-ChildItem Count 1 result

This is going to be a quick one. I'm working on a new Powershell script (my second) and I'm doing some sanity checks before I actually try to continue the workflow.

If you run the command below and it returns only one item and then either try to print out $fileCount or run an if statement or something against it like if ($fileCount -gt 0){do some stuff} the "do some stuff" won't happen.
#$fileCount = $(get-childitem C:\ -filter *.zip).count

This is because the count method returns an array, which if only one item is in it doesn't get created and thus is 0.   To get around this you must create the array first. You can do this in the same line of code as shown below.

#$fileCount = @(get-childitem C:\ -filter *.zip).count

The at sign there will create the array and you will have one item in it.


No comments: