The Measure-Object cmdlet counts objects. But it can do even more. We can calculate the sum, the average and much more. In this blog post I show a few examples with Measure-Object. Let’s dive in.
First of First of all, we can call up the help for Measure-Object here:
Now I have prepared a few examples. I recommend copying these examples into ISE or VS Code and executing them there to learn the mechanics and the possibilities of this cmdlet.
Here we go:
# Measure-Object
$numbers = 1,2,3,4,5,6,7,8,9,10
$numbers | Measure-Object -Average -Maximum -Minimum -Sum
$array = "apple", "banana", "cherry"
$array | Measure-Object
$array = "apple", "banana", "cherry"
$array | Measure-Object -Maximum -Property Length
$text = "Hello, world!"
$text | Measure-Object -Line -Word -Character
"One", "Two", "Three", "Four" | Set-Content -Path $home\tmp.txt
Get-Content $home\tmp.txt | Measure-Object -Character -Line -Word
# Measure-Object in Real-World Scenarios
# Count Commands
Get-Command | Measure-Object | Select-Object -Property Count
# Cound ADUsers
Get-ADUser -Filter 'LogonCount -eq "0"' -Properties LogonCount | Measure-Object
# Count Sum of Files in a Folder and Subfolders
(Get-ChildItem -Path "C:\Users\PatrickGruenauersid-\SynologyDrive\Videos\Udemy" -Recurse -Include *.mp4 |
Measure-Object Length -Sum).Sum /1GB
I hope you were able to learn a few things from this blog post that you can put into practice. See you next time!
Categories: PowerShell




2 replies »