Update "Manager" attribute for Active Directory when importing from a CSV

LeeDH 21 Reputation points
2022-01-21T13:49:23.69+00:00

I have a weird issue regards updating the "manager" field when importing from a CSV.

The following works when updating one at a time:
$user = "fred.smith"
$manager = "jane.doe"
$SamAccountName = $user
$GADuser = Get-ADUser -Filter {SamAccountName -eq $SamAccountName} -ErrorAction Stop
$GADuser | Set-ADuser -Manager $Manager -ErrorAction Stop

However, the following errors out when updating and I don't know why:
$File = "C:\temp\dr.csv"
$theuser = Import-Csv -Path $File
foreach ($user in $theuser) {
$SamAccountName = $user.Name
$manager = $user.newmanager
Try {
$GADuser = Get-ADUser -Filter {SamAccountName -eq $SamAccountName} -ErrorAction Stop
$GADuser | Set-ADuser -Manager $manager -ErrorAction Stop
}
catch {
Write-Error -Message "$SamAccountName or its manager does not exist please check in Active Directory"
}
}

Contents of the dr.csv file are:
name,newmanager
fred.smith,jane.doe
joe.smythe,jane.doe
helen.smith,jane.doe

As very similar commands to the update one at a time section but doesn't like it.

Any help would be appreciated.

Many thanks

Windows for business Windows Client for IT Pros Directory services Active Directory
Windows for business Windows Server User experience PowerShell
0 comments No comments
{count} votes

Accepted answer
  1. Rich Matheisen 47,901 Reputation points
    2022-01-21T16:09:12.477+00:00

    The first thing that comes to mind is that there are leading or trailing spaces in either the 'name' or 'newmanager' properties.
    The second is that your Get-ADUser is depending on the "-ErrorAction STOP" to prevent the Set-ADUser from executing. Unfortunaely that won't happen. Because you're using the -Filter parameter the expected terminating error will never happen of the cmdlet doesn't find a match.

    See if this helps:

    $File = "C:\temp\dr.csv"
    $theuser = Import-Csv -Path $File
    foreach ($user in $theuser) {
        $SamAccountName = $user.Name.Trim()
        $manager = $user.newmanager.Trim()
        Try {
            $GADuser = Get-ADUser -Filter { SamAccountName -eq $SamAccountName }
            if ($null -eq $GADuser){
                Write-Error -Message "$SamAccountName does not exist."
            }
            else{
                $GADuser | Set-ADUser -Manager $manager -ErrorAction Stop
            }
        }
        catch {
            Write-Error -Message "The manager '$manager' account for user '$SamAccountName' does not exist please check in Active Directory"
        }
    }
    

    BTW, replacing the information in the exception with a generic "something bad happened" doesn't help you to understand what the problem is. :-)

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.