Search code examples
powershellactive-directorywindows-server-2012ou

Update users in AD in specific OU with PowerShell


Let's say I have below OU tree:

DataManagement
└─Country
  ├─Germany
  │ └─Users
  │   ├─Laptops
  │   └─Computers
  ├─France
  │ └─Users
  │   ├─Laptops
  │   └─Computers
  etc.

I would like to update specific container in OU, for example, users in laptops group in France. How to do that if I would like to import users from CSV? Below code check and update all OU. Unfortunately, I have no idea how to select a specific container. Any suggestions?

Import-Module ActiveDirectory
$Userscsv = Import-Csv D:\areile\Desktop\adtest.csv

foreach ($User in $Userscsv) {
    Set-ADUser $User.SamAccountName -Replace @{
        Division = $User.Division;
        Office   = $User.Office;
        City     = $User.City
    }
}

Solution

  • Ah, it would have helped if you have shown us (part) of the content of the csv then.

    However, i think this will work for you:

    Import-Module ActiveDirectory
    $UsersCsv = Import-Csv D:\areile\Desktop\adtest.csv
    
    $SearchBase = "<DISTINGHUISHEDNAME-OF-THE-FRENCH-USERS-OU>"
    
    foreach ($usr in $UsersCsv) {
        $adUser = Get-ADUser -Filter {EmailAdress -eq '$($usr.Email)'} -SearchBase $SearchBase -Properties Division,Office,City,EmailAddress
        if ($null -ne $adUser) {
            Set-ADUser $adUser.SamAccountName -Replace @{Division = $usr.Division; Office = $usr.Office; City = $usr.City}
        }
    }