Forum Discussion

Baron164's avatar
Baron164
Brass Contributor
Jun 24, 2022

Need help importing user data from csv

I need to fill in the Manager Attribute for employee accounts using a CSV export from HR. I have the added bonus of the fact that SamAccountNames do not follow a consistent naming convention. So I ne...
  • LainRobertson's avatar
    LainRobertson
    Jun 28, 2022

    Harm_Veenstra 

     

    Hey, Harm.

     

    I'd strongly recommend using the -Filter parameter in the Get-AD* calls, as you're current pulling every single user in Active Directory client-side before filtering anything - twice.

     

    In smaller environments, that won't be an issue, but it'll run into scalability issues rather quickly.

     

    Using your original example, something like this would be more efficient in medium to large directories:

     

    $csv = import-csv c:\scripts\accounts.csv
    foreach ($line in $csv) {
        $user = Get-ADUser -Filter "employeeID -eq '$($line.EmployeeID)'";          # Here, we're now leveraging server-side filtering.
        $manager = Get-ADUser -Filter "employeeID -eq '$($line.SupervisorID)'";     # And again here.
    
        if ($user -is [Microsoft.ActiveDirectory.Management.ADUser] -and $manager -is [Microsoft.ActiveDirectory.Management.ADUser])
        {
            # We only want to be in here where we got precisely one user and one manager, otherwise we have no way to arbitrate who gets updated with what.
            Set-ADUser $user -Manager $manager
        }
    }

     

    Cheers,

    Lain

Resources