"Count" Available in PowerShell 3.0

by Nov 30, 2012

Finally, the property Count is available on all objects in PowerShell 3.0. This solves a great problem because it allows you to count results even if they are not wrapped in an array. Have a look:

PS> (Get-ChildItem $env:windir\*.txt).Count
2
PS> (Get-ChildItem $env:windir\explorer.exe).Count
1
PS> (Get-ChildItem $env:windir\nothing.there -ErrorAction SilentlyContinue).Count
0

In PowerShell 2.0, this would have returned 2 for the first call, an exception for the second (since there is only one explorer.exe, PowerShell does not wrap it into an array) and nothing for the last call. That's why in PowerShell 2.0, you would have to manually wrap results into an array (and still need to do if you want your code to be compatible to PowerShell 2.0). This code runs in all versions of PowerShell:

PS> @(Get-ChildItem $env:windir\*.txt).Count
2
PS> @(Get-ChildItem $env:windir\explorer.exe).Count
1
PS> @(Get-ChildItem $env:windir\nothing.there -ErrorAction SilentlyContinue).Count
0

Another reason why the "old" syntax may be better than the new: once you enable Strict-Mode, the behavior falls back to PowerShell 2.0 standards and breaks the new syntax.

Twitter This Tip! ReTweet this Tip!