Measure-Object
To count the number of objects in PowerShell, you can use the Measure-Object
cmdlet.
This cmdlet allows you to count the number of objects in a collection, as well as perform other calculations on the objects, such as calculating the sum, average, minimum, or maximum value of a property of the objects.
Here is an example of how you can use the Measure-Object
cmdlet to count the number of objects in a collection:
# Count the number of objects in a collection
$objectCount = Measure-Object -InputObject <object_collection> -Count
# Print the number of objects
Write-Host "The collection contains $objectCount objects."
In the example above, the Measure-Object
cmdlet is used to count the number of objects in the collection specified by <object_collection>
.
The resulting count is stored in the $objectCount
variable, and then printed to the PowerShell console using the Write-Host
cmdlet.
Count
property of Measure-Object
Alternatively, you can use the Count
property of the Measure-Object
cmdlet to get the number of objects in a collection.
Here is an example of how you can use the Count
property to count the number of objects in a collection:
# Count the number of objects in a collection
$objectCount = <object_collection> | Measure-Object | Select-Object -ExpandProperty Count
# Print the number of objects
Write-Host "The collection contains $objectCount objects."
In the example above, the Measure-Object
cmdlet is used to measure the objects in the collection specified by <object_collection>
.
The Select-Object
cmdlet is then used to select the Count
property of the resulting Measure-Object
output, and expand it into a simple value.
The resulting value is stored in the $objectCount
variable, and then printed to the PowerShell console using the Write-Host
cmdlet.
Either of these methods can be used to count the number of objects in a collection in PowerShell. You can use this information to perform various operations on the objects in the collection, such as filtering or sorting the objects based on their count.
Related tutorials curated for you
How to run a .bat file in PowerShell
How to create a directory in PowerShell
How to find special characters in PowerShell
Get the full path of ChildItem in PowerShell
How to rename a folder in PowerShell
Everything about certificates in PowerShell
What are verbs in PowerShell?
PowerShell vs. Bash
How to create new items in PowerShell
How to use Start-Job in PowerShell
How to declare global variables in PowerShell
How to use If Else in PowerShell