Q. What is the quickest way to get an object count in Windows PowerShell?

John Savill

May 27, 2008

1 Min Read
ITPro Today logo

A. In my April 15, 2008, FAQ ("Q: How can I use Windows PowerShell to get a count of all of my machine's services?"), I created a service count using a Foreach loop, which increased a counter by 1 for each object returned from the Get-Service command, as the following code shows:

get-service | foreach {$t=0} {$t +=1} {"Total services: $t"}

A number of readers pointed out that I should've used the Measure-Object cmdlet with the following commands:

get-service | measure-object | select count

The output would be:

Count
  -----
  152

If I hadn't included the | select count command, the computer would have outputted other counts that don't apply to what I wanted, such as information about averages, sums, maximums, and minimums of the values passed.

About the Author(s)

Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like