How to use the command `Measure-Object` (with examples)
- Windows
- December 25, 2023
The Measure-Object
command is a powerful tool in PowerShell that allows you to calculate the numeric properties of objects, as well as count characters, words, and lines in string objects such as text files. It provides valuable information and statistics about the data you are working with.
Use case 1: Count the files and folders in a directory
Code:
Get-ChildItem | Measure-Object
Motivation:
If you want to quickly count the number of files and folders in a directory, the Measure-Object
command is perfect for the job. By piping the output of the Get-ChildItem
command (which lists all the files and folders in a directory) to Measure-Object
, you can easily obtain the count.
Explanation:
Get-ChildItem
: This command lists all the files and folders in a given directory.|
Pipe: This operator takes the output of the previous command and passes it as input to the next command.Measure-Object
: This command calculates the numeric properties of the objects passed to it, in this case, the files and folders.
Example output:
Count : 10
Average :
Sum :
Maximum :
Minimum :
Property :
This output shows that there are 10 files and folders in the specified directory.
Use case 2: Pipe input to Measure-Command
Code:
"One", "Two", "Three", "Four" | Set-Content -Path "path\to\file"; Get-Content "path\to\file"; | Measure-Object -Character -Line -Word
Motivation:
If you want to measure the character, line, and word count of a specific string or text file, you can use the Measure-Object
command along with piping. This can be useful when analyzing or validating text data.
Explanation:
"One", "Two", "Three", "Four"
: This creates an array of strings.|
Pipe: This operator passes the output of the previous command as input to the next command.Set-Content -Path "path\to\file"
: This command writes the array of strings to a file specified by the path.Get-Content "path\to\file"
: This command retrieves the content of the file.Measure-Object -Character -Line -Word
: This command calculates the character count, line count, and word count of the input passed to it.
Example output:
Lines Words Characters Property
----- ----- ---------- --------
1 4 4 System.Object[]
This output shows that the input string has 1 line, 4 words, and 4 characters.
Conclusion:
The Measure-Object
command in PowerShell provides a convenient way to calculate numeric properties and count characters, words, and lines in objects. It is a versatile tool for data analysis, statistics, and text processing tasks.