如何修改PowerShell脚本以遍历域内所有AD组并统计账户总数与禁用账户数(输出至CSV)
PowerShell Script to Count Total & Disabled Accounts for All AD Groups
Got it, let's tweak your original script to cover all AD groups in your domain and output the stats to a properly formatted CSV. Here's the complete working script:
# Initialize an empty array to store our statistics $groupStats = @() # Fetch all AD groups in the domain, including their member list $allADGroups = Get-ADGroup -Filter * -Properties Members # Loop through each group to calculate totals foreach ($group in $allADGroups) { # Get only user members from the group (skip nested groups/computers) $groupUsers = Get-ADUser -Filter {DistinguishedName -in $group.Members} -ErrorAction SilentlyContinue # Calculate total and disabled user counts $totalUsers = $groupUsers.Count $disabledUsers = ($groupUsers | Where-Object {-not $_.Enabled}).Count # Create a structured object for the results $statsEntry = [PSCustomObject]@{ "AD group name" = $group.Name "Total AD account" = $totalUsers "Total Disabled AD account" = $disabledUsers } # Add the entry to our results array $groupStats += $statsEntry } # Export results to CSV (update the file path as needed) $groupStats | Export-Csv -Path "C:\Temp\AD_Group_User_Stats.csv" -NoTypeInformation -Encoding UTF8 Write-Host "Done! Statistics saved to C:\Temp\AD_Group_User_Stats.csv"
Key Notes:
- Fetching all groups:
Get-ADGroup -Filter *grabs every group in your domain, and-Properties Membersensures we load the member list for each group. - Filtering user members: Using
Get-ADUserwith a filter onDistinguishedNameensures we only pull actual user accounts (ignoring nested groups, computer objects, etc.). - Structured output: We use
[PSCustomObject]to create consistent columns that map perfectly to your required CSV format. - CSV export:
-NoTypeInformationremoves the unnecessary type header in the CSV, and-Encoding UTF8ensures special characters display correctly.
Optional: Include Nested Group Members
If you need to count users in nested groups too (not just direct members), replace the $groupUsers line with this:
$groupUsers = Get-ADGroupMember -Identity $group -Recursive | Where-Object {$_.objectClass -eq 'user'} | Get-ADUser -ErrorAction SilentlyContinue
This will recursively pull all users from nested subgroups and include them in your totals.
内容的提问来源于stack exchange,提问作者Senior Systems Engineer
相关产品推荐
相关产品推荐

