Quantcast
Channel: PowerShell.org » All Posts
Viewing all articles
Browse latest Browse all 13067

Reply To: Help Iterating Through .CSV File to Update AD

$
0
0

I created an InputFile that looks like this:

"EmployeeID"|"Assistant"|"Manager"
"1"|"2"|"3"
"2"|""|"1"
"3"|"5"|"6"
"4"|"5"|"6"
"5"|"6"|""
"6"|"7"|""
"7"|""|"6"

Assuming that more than one person shares the same manager and that an assistant can assist more than one person, it is likely that the same ID will show up in the inputfile more than once.

To minimize the number of queries to Active Directory, I first extract each unique ID in the input-file and store these in $AllUserIDs.

For each unique ID found I query Active Directory for a distinguished name and add that value to a hashtable where EmployeeID is the key.

Now just import the csv again and loop through each row setting the attributes assistant and manager by using references to the hashtable.

Add-PSSnapin -Name Quest.ActiveRoles.ADManagement
$OU = "OU=Staff,DC=simon,DC=lab,DC=lcl"
$InputFile = '.\InputFile.csv'
$AllUserIDs = Import-Csv -Delimiter '|' -Path $InputFile | 
    ForEach-Object {
        $_.EmployeeID
        $_.Assistant
        $_.Manager
    } | Where-Object {$_ -ne $null} | Sort-Object -Unique
 
$AllUsers = @{}
Foreach($UserID in $AllUserIDs)
{
    $DN = Get-QADUser -SearchRoot $OU -Sizelimit 0 -ObjectAttributes @{employeeID=$UserID} | 
        Select-Object -ExpandProperty DN
    $AllUsers.Add($UserID,$DN)
}
 
Import-Csv -Delimiter '|' -Path $InputFile | Foreach {
    Set-QADUser -Identity $AllUsers["$($_.EmployeeID)"] -Manager $AllUsers["$($_.Manager)"] -ObjectAttributes @{Assistant=$AllUsers["$($_.Assistant)"]}
}

I tried to utilize the pipeline as much as possible to lessen the amount of memory used if the csv-file is huge. For smaller files it might be faster to store the imported csv in a variable and using Foreach instead of Foreach-Object.


Viewing all articles
Browse latest Browse all 13067