PowerShell Tip of the Week: Count occurrence of each element

occurrence

How to count the occurrence of each element. Today I would like to share a few examples describing how it can be done. To do this we can use Group-Object cmdlet.

Count the occurrence

The Group-Object cmdlet displays objects in groups based on the value of a specified property. Group-Objectreturns a table with one row for each property value and a column that displays the number of items with that value.

Example:

Get unique processes count:

occurrence
Get-Process | Group-Object -NoElement | Select-Object name,count  | Sort count -Descending -Unique

Example:

Get files recursively and count occurrence. Display count greater than 1:

occurrence
$Files = Get-ChildItem -Path "c:\users\pawel.janowicz\desktop" -Recurse 
$Files | Group-Object -NoElement | Select-Object name,count | Sort count -Descending | where {$_.count -gt 1}

Example:

Get location count for currently locked users:

occurrence
# Setup array
$LockedUsers = @()
 
#=======================================================================
# Checking first 100 locked users
Search-ADAccount -LockedOut | select -first 100 | foreach{
    $City = $Object = $Null
    $City = (Get-ADUser -Identity $_.name -Properties City).City
    $Object = New-Object PSObject -Property ([ordered]@{ 
        Name         = $_.name
        Locked       = $_.lockedout
        Location     = $City
        UPN          = $_.UserPrincipalName        
    })
    $LockedUsers += $Object
}

# Group and count occurence of each location
$LocationCount = $LockedUsers.location | Group-Object -NoElement | Select-Object name,count | Sort count -Descending

# Display results in console
$LocationCount

Example:

Get events from remote machines and count the occurrence of event IDs and machine names:

occurrence
    # Servers
    $Servers = Get-Content -path "D:\scripts\Input.txt"
    $Results = @()

    # Get events
    $Results = Invoke-Command -cn $Servers {
        
        $filter = @{
            Logname = 'System'
            ID = 142,139,35,38,24,29,50
        }
        Get-WinEvent -FilterHashtable $filter 
 
    } | select MachineName,TimeCreated,ID,Message 

    # Count event IDs
    $Results.ID | Group-Object -NoElement | Select-Object name,count | Sort count -Descending

    # Count machinename
    $Results.MachineName | Group-Object -NoElement | Select-Object name,count | Sort count -Descending

I hope that this was informative for you 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.