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

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<br>  -----<br>  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.

Please or Register to post comments.

Upcoming Training

Mastering System Center 2012

During over 6 hours of training you can join John Savill from your computer as he will walk you through the key components and capabilities of System Center 2012, what’s involved in using the components, and the benefit they can bring to your environment.

Register Now

Current Issue

May 2013 - The NameTranslate object is useful when you need to translate Active Directory object names between different formats, but it's awkward to use from PowerShell. Here's a PowerShell script that eliminates the awkwardness.

CURRENT ISSUE / ARCHIVE / SUBSCRIBE

Windows Forums

Get answers to questions, share tips, and engage with the Windows Community in our Forums.