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

PowerShell脚本检测AD用户状态结果异常,寻求排查方案

问题描述

我尝试通过PowerShell脚本导入用户ID列表,检查Active Directory(AD)中对应账户是否仍处于活跃状态。但运行脚本后生成的CSV文件显示所有ID均为“Removed”,与手动核对结果不符。此外,移除脚本中的try/catch块后,会出现“$userID未定义”的错误,以及Get-ADUser的InvalidArgument异常。相关脚本如下:

# Import the CSV file
$csvPath = "File path\User IDs.csv"
$users = Import-Csv $csvPath

# Initialize an array to store the results
$results = @()

# Initialize the $userID variable outside of the foreach loop
$userID = $null

# Iterate over each user ID
foreach ($user in $users) {
    
    $userID = $user.ID

    try {

    # Check AD for account status
    $adUser = Get-ADUser -Identity $userID -Properties Enabled

    # Determine if the account is active
    $isActive = if ($adUser.Enabled -eq $true) { "Active" } else { "Inactive" }

    # Create a custom object with the ID and Active? properties
    $result = [PSCustomObject]@{
        ID = $userID
        "Active?" = $isActive
    }

    # Add the result to the array
    $results += $result

    } catch {

        Write-Host "$userID not found in Active Directory"

        # Create a custom object with the ID and Active? properties
        $result = [PSCustomObject]@{
            ID = $userID
            "Active?" = "Removed"
    }

        # Add the result to the array
        $results += $result

    }

}


# Export the results to a new CSV file
$resultsPath = "File path\Active IDs.csv"
$results | Export-Csv -Path $resultsPath -NoTypeInformation
问题排查与修复方案

1. 核对CSV文件的列标题

脚本中用$user.ID获取用户ID,这要求你的CSV文件第一行的列标题必须是ID(PowerShell对大小写敏感)。如果列标题是其他内容(比如“UserID”“员工号”),$user.ID会返回空值,导致Get-ADUser无法找到用户,直接进入catch块标记为“Removed”。

  • 修复:打开CSV文件确认列标题为ID;如果不是,要么修改CSV的列标题,要么把脚本里的$user.ID改成对应列名(比如列标题是“UserID”就改成$user.UserID)。

2. 调整Get-ADUser的搜索逻辑

如果你的用户ID不是AD账户默认的标识属性(比如SAM账户名、SID、可分辨名称),直接用-Identity参数会找不到用户。比如ID是员工号(EmployeeID),需要用-Filter参数指定搜索属性:

  • 将脚本中的Get-ADUser行修改为:
$adUser = Get-ADUser -Filter "EmployeeID -eq '$userID'" -Properties Enabled -ErrorAction Stop

注意:如果ID包含单引号,需要先转义,避免Filter语法错误:$userID = $userID -replace "'", "''"

3. 修复try/catch的错误捕获逻辑

默认情况下,Get-ADUser找不到用户时抛出的是非终止错误,try/catch不会捕获。必须加上-ErrorAction Stop,才能让错误触发catch块:

  • 在Get-ADUser命令末尾添加-ErrorAction Stop,确保找不到用户时进入catch逻辑。

4. 解决“$userID未定义”的错误

即使在循环外初始化了$userID = $null,如果CSV存在空白行,$user.ID会返回空值,可能导致后续逻辑出错。可以在循环里先判断ID是否有效:

foreach ($user in $users) {
    $userID = $user.ID.Trim() # 去除前后空格
    if ([string]::IsNullOrWhiteSpace($userID)) {
        Write-Host "跳过空白ID行"
        continue
    }
    # 后续try/catch逻辑...
}

修复后的完整脚本示例

# Import the CSV file
$csvPath = "File path\User IDs.csv"
$users = Import-Csv $csvPath

# Initialize an array to store the results
$results = @()

# Iterate over each user ID
foreach ($user in $users) {
    $userID = $user.ID.Trim()
    if ([string]::IsNullOrWhiteSpace($userID)) {
        Write-Host "跳过空白ID行"
        continue
    }

    try {
        # 假设ID是EmployeeID,根据实际情况修改Filter条件
        $adUser = Get-ADUser -Filter "EmployeeID -eq '$userID'" -Properties Enabled -ErrorAction Stop

        # 判断账户活跃状态
        $isActive = if ($adUser.Enabled -eq $true) { "Active" } else { "Inactive" }

        # 构造结果对象
        $result = [PSCustomObject]@{
            ID = $userID
            "Active?" = $isActive
        }

        $results += $result

    } catch {
        Write-Host "$userID 未在Active Directory中找到"

        $result = [PSCustomObject]@{
            ID = $userID
            "Active?" = "Removed"
        }

        $results += $result
    }
}

# 导出结果到CSV
$resultsPath = "File path\Active IDs.csv"
$results | Export-Csv -Path $resultsPath -NoTypeInformation

内容的提问来源于stack exchange,提问作者Tek_Sten

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 15:45:06