SuperDOS
SuperDOS

Reputation: 331

nested foreach loop powershell

I have exports from two systems in two separate csv files.

These files contain a lot of different data but just to keep the question simple let's say one of them contains the email and username and the other one contains mobile numbers and email.

What I want to do is run a foreach loop that updates an attribute in the ad and within the loop run an another foreach loop to update the mobile number in the ad.

How can I match the email from the first list in the second nested foreach loop and get the row?

The script I already wrote:

    $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
        }
    }

Upvotes: 0

Views: 159

Answers (1)

Ivan Mirchev
Ivan Mirchev

Reputation: 839

I do not have the content of the files, so improvising a bit, but hopefully you'll get the idea. Why you need a second loop? I assume that the e-mail address is the unique identifier in both files? Then you may loop the first one, to get each ad user details and based on the mail, search in the second file, to get the phone and add it. For example

$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
    }
}

What do you think about that as a scenario?

Upvotes: 1

Related Questions