You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改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 Members ensures we load the member list for each group.
  • Filtering user members: Using Get-ADUser with a filter on DistinguishedName ensures 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: -NoTypeInformation removes the unnecessary type header in the CSV, and -Encoding UTF8 ensures 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 19:22:31