无法通过 PS 检查 AD 中的用户 ID 是否处于活动状态

问题描述 投票:0回答:1

我正在尝试加载用户列表,并希望针对 AD 运行每个用户,以查看他们的帐户在 AD 中是否仍然处于活动状态。当我运行下面的 PS 脚本时,我得到一个 CSV 文件,其中显示每个 ID 都已被删除,但手动检查显示这是不正确的。

# 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

我对编程世界还很陌生,所以我试图理解我哪里出了问题。谢谢!

我在没有 try {} 和 catch {} 的情况下尝试了脚本,但是它会给我错误:在表达式中找不到 'userID':$userID 未定义,然后会给 Get-ADUser、ArgumentException 提供 InvalidArgument 错误

powershell active-directory
1个回答
0
投票

正如您在评论中所说:

CSV 文件没有文件头,我确保在运行脚本之前将其删除。该列表包含 samAccountNames。

那么

Import-Csv
不是导入文件的正确 cmdlet,因为您的文件不是 Csv,请使用
Get-Content
来读取文件内容。经过一些改进后的最终代码是:

# Path to the txt file with samAccountNames
$filePath = 'File path\User IDs.txt'
# Export path
$resultsPath = 'File path\Active IDs.csv'

Get-Content $filePath | ForEach-Object {
    try {
        $adUser = Get-ADUser -Identity $_
        if ($adUser.Enabled) {
            $isActive = 'Active'
        }
        else {
            $isActive = 'Inactive'
        }
    }
    catch {
        Write-Warning $_
        $isActive = 'Removed'
    }

    [PSCustomObject]@{
        ID        = $_
        'Active?' = $isActive
    }
} | Export-Csv -Path $resultsPath -NoTypeInformation
© www.soinside.com 2019 - 2024. All rights reserved.