簡體   English   中英

嵌套的foreach循環powershell

[英]nested foreach loop powershell

我在兩個單獨的 csv 文件中從兩個系統導出。

這些文件包含許多不同的數據,但為了簡單起見,假設其中一個包含emailusername ,另一個包含mobile numbersemail

我想要做的是運行一個foreach循環來更新廣告中的屬性,並在循環內運行另一個foreach循環來更新廣告中的手機號碼。

如何匹配第二個嵌套foreach循環中第一個列表中的email並獲取行?

我已經寫的腳本:

    $users = import-csv -path C:\temp\list1.csv
    $users2 = import-csv -path c:\temp\list2.csv

    Foreach ($user in $users) {
        try {
            $aduser = get-aduser -Filter "mail -eq '$($user.mail)'" -properties *
        }
        catch {
            $aduser = $null
            Write-host "No aduser found"
            Continue
        }
        if ($user.username -ne $aduser.EmployeeID) {
            set-aduser $aduser -EmployeeID $user.username
        }
        Foreach ($user2 in $users2) {
            if ($user.mobile -ne $aduser.mobile) {
                set-aduser $aduser -MobilePhone $user.mobile
        }
    }

我沒有文件的內容,所以有點即興發揮,但希望你能明白。 為什么需要第二個循環? 我假設電子郵件地址是兩個文件中的唯一標識符? 然后你可以循環第一個,獲取每個廣告用戶的詳細信息,並根據郵件,在第二個文件中搜索,獲取電話並添加它。 例如

$users = import-csv -path C:\temp\list1.csv
$users2 = import-csv -path c:\temp\list2.csv

# loop the users
Foreach ($user in $users) {
    try {
        #get ad user details and check if existing
        $aduser = get-aduser -Filter "mail -eq '$($user.mail)'" -properties *

        # Get the mobile from the second list, using the mail from the current loop
        $Mobile = ($users2 | Where-Object -Property Mail -eq $user.mail)

        # Set EmployeeID
        if ($user.username -ne $aduser.EmployeeID) {
            set-aduser $aduser -EmployeeID $user.username
        }

        #Set Mobile
        if ($Mobile -ne $aduser.mobile) {
            set-aduser $aduser -MobilePhone $Mobile
        }
    }
    catch {
        $aduser = $null
        Write-host "No aduser found"
        Continue
    }
}

作為一個場景,你怎么看?

暫無
暫無

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

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