簡體   English   中英

Powershell 腳本檢查用戶是否存在於 Active Directory 中並導出到 csv

[英]Powershell script check if user exists in Active Directory and export to csv

我有一個現有的腳本,它可以檢查給定用戶是否存在於 AD 中。 但我無法將結果導出到 csv 文件中。 請幫忙。

Clear-Host
$UserList = gc .\Output_userInfo.csv
$outputFilePath = "D:\Input\User&Group_Output.csv"
foreach ($u in $UserList) {
    try {
        $ADUser = Get-ADUser -Identity $u -ErrorAction Stop 
    }
    catch { 
        if ($_ -like "Cannot find an object with identity: '$u'") { 
            "User '$u' does not exist." | Export-Csv .\notexists.csv -NoTypeInformation -Force 
        }
        else { 
            "An error occurred: $_" 
        } continue 
    } 
    "User '$($ADUser.SamAccountName)' exists." | 
    Export-Csv .\notexists.csv -NoTypeInformation -Force 
}
$UserList = gc C:\temp\Output_userInfo.csv #use full path instead. .\ is relative path and could cause issues if you are not careful
$outputFilePath = "D:\Input\User&Group_Output.csv"

$finalResult = foreach ($u in $UserList)
{
    #CSV takes data in a table format. So best to replicate that with a PS Cusotm object that can easily be represented ina table format.
    $obj = [PSCustomObject]@{
        UserName = $u
        Status = ""
    }
    try
    {
        $ADUser = Get-ADUser -Identity $u -ErrorAction Stop
        $obj.Status = "Exists"
    }
    catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException]
    {
        $obj.Status = "Does not Exist"
    }
    catch
    {
        $obj.Status = $_.Exception.Message
    }
    $obj
}

$finalResult | Export-Csv -Path $outputFilePath -NoTypeInformation -Force

如果您想知道我是如何知道第一次捕獲中使用的錯誤類型的,您可以通過模擬錯誤來找到它[在這種情況下, get-aduser blah會這樣做,因為這樣的用戶不存在]。 然后你可以用select *展開最后一條錯誤消息,如圖所示,查看異常類型。 或者,您也可以嘗試閱讀文檔,但我沒有那種耐心。

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM