簡體   English   中英

AD 查詢到 .txt 文件以刪除現有用戶的 .csv 中的行

[英]AD Query into .txt file to remove line in .csv of existing users

我在這里使用一段代碼,它使用帶有用戶名列表的 Master.txt 文件,它查詢 Active Directory 並檢查他們是否是用戶。 之后,它會填充兩個單獨的 .txt 文件,稱為 UserExists 和 UserDoesntExist。

$Users = Get-Content "Desktop\Master.txt"
ForEach ($User in $Users)
{
    $UserObj = $(try {Get-ADUser $User} catch {$Null})
    If ($UserObj -ne $Null)
    {
       Write-Host "$User Exists" -BackgroundColor Green -ForegroundColor Yellow
       Add-Content 'Desktop\UserExists.txt' "$User"
    }
    else
    {
       Write-Host "$User Doesn't Exist" -BackgroundColor Red -ForegroundColor Yellow
       Add-Content 'Desktop\UserDoesntExist.txt' "$User"
     }
}

這兩個列表按預期工作,還有一個 .csv 文件,其中包含 master.txt 文件中的每個用戶,但在密碼等和其他字段中包含用於創建用戶的標題。 但我想根據 .txt 文件刪除 .csv 中用戶已經存在的行。 有沒有辦法讀取 UserExists 的 .txt 文檔,然后在 .csv 中查找匹配的用戶名並刪除該行? 這是 .csv 和 .txt 文件中的一個字段,因此它會匹配。 這是可行的嗎? 任何幫助和建議都會非常感激。

這是您可以做到的一種方法,希望內聯注釋可以幫助您了解邏輯:

$Users = Get-Content "Desktop\Master.txt"
# import the csv
$Csv = Import-Csv "Path\To\Csv.csv"

$output = ForEach ($User in $Users) {
    # if the user could be found this condition and assignment holds `$true`
    If ($UserObj = Get-ADUser -LDAPFilter "(samAccountName=$User)") {
        # output this user's `SamAccountName` (which is captured in `$output`)
        $UserObj.SamAccountName
        Write-Host "$User Exists" -BackgroundColor Green -ForegroundColor Yellow
        Add-Content 'Desktop\UserExists.txt' "$User"
        # go to next user
        continue
    }
    Write-Host "$User Doesn't Exist" -BackgroundColor Red -ForegroundColor Yellow
    Add-Content 'Desktop\UserDoesntExist.txt' "$User"
}

# filter the Csv where the `Username` column is not in the `$output` array
$csv.Where{ $_.Username -notin $output } |
    # and export the filtered Csv
    Export-Csv "path\to\filteredCsv.csv" -NoTypeInformation

暫無
暫無

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

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