powershell icon 17209 400x400

Powershell – Excel Report aller User in OUs

cropped Andreas Hartig 003Veröffentlicht von

Mit Powershell lässt sich einfach und schnell ein Excel Report erstellen, der die Userobjekte in allen OUs zählt und das Ergebnis in eine Excel Tabelle schreibt.

Dazu einfach folgendes Skript benutzen:

<#
.SYNOPSIS
This script counts the number of users in each organizational unit (OU) in an Active Directory (AD) environment and exports the results to a CSV file encoded in UTF-8.

.DESCRIPTION
The script uses the Get-ADOrganizationalUnit cmdlet to retrieve all the OUs in the AD environment. The DistinguishedName property of each OU is then stored in the $ous variable. 
A foreach loop is then used to iterate through each of the OUs. Inside the loop, the Get-ADUser cmdlet is used to search for all users in the current OU, and the output is piped to the Measure-Object cmdlet to count the number of users.
For each iteration, a new object is created using the New-Object cmdlet, which contains the OU name and the user count. These objects are then added to the `$results` array.
After the foreach loop, the $results array is piped to the Export-Csv cmdlet, which exports the data to a CSV file named "user_count_by_ou.csv"  in the current directory with UTF8 encoding and without type information.

.EXAMPLE
.\Count-ADUsersByOU.ps1
#>

$ous = (Get-ADOrganizationalUnit -Filter *).DistinguishedName
$results = @()
foreach ($ou in $ous) {
    $userCount = (Get-ADUser -Filter * -SearchBase $ou | Measure-Object).Count
    $results += New-Object PSObject -Property @{
        OU = $ou
        UserCount = $userCount
    }
}
$results | Export-Csv -Path "user_count_by_ou.csv" -Encoding UTF8 -NoTypeInformation

Kommentar hinterlassen