How to count objects in PowerShell?

后端 未结 5 2170
星月不相逢
星月不相逢 2020-12-07 14:17

As I\'m reading in the PowerShell user guide, one of the core PowerShell concepts is that commands accept and return objects instead of text. So for example, runnin

5条回答
  •  暖寄归人
    2020-12-07 15:09

    As short as @jumbo's answer is :-) you can do it even more tersely. This just returns the Count property of the array returned by the antecedent sub-expression:

    @(Get-Alias).Count
    

    A couple points to note:

    1. You can put an arbitrarily complex expression in place of Get-Alias, for example:

      @(Get-Process | ? { $_.ProcessName -eq "svchost" }).Count
      
    2. The initial at-sign (@) is necessary for a robust solution. As long as the answer is two or greater you will get an equivalent answer with or without the @, but when the answer is zero or one you will get no output unless you have the @ sign! (It forces the Count property to exist by forcing the output to be an array.)

    2012.01.30 Update

    The above is true for PowerShell V2. One of the new features of PowerShell V3 is that you do have a Count property even for singletons, so the at-sign becomes unimportant for this scenario.

提交回复
热议问题