Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Updating Active Directory via PowerShell

Hallo I got a question with my update script for my active directory
I am trying to update a user using .csv document
It’s for my understanding very simple but there is an error which I cant find out why it occurs.

My Script:

#Get CSV content
 $CSVrecords = Import-Csv "C:\scripts\test.csv" -Delimiter ";"
    
 #Create arrays for skipped and failed users
 $SkippedUsers = @()
 $FailedUsers = @()
    
 #Loop trough CSV records
 foreach ($CSVrecord in $CSVrecords) {
         $upn = $CSVrecord.UserPrincipalName
         $user = Get-ADUser -Filter "userPrincipalName -eq '$upn'"
         if ($user) {
                 try {
                         $user | Set-ADUser -Department $CSVrecord.Department -Company $CSVrecord.Company -ErrorAction STOP
                 }
                 catch {
                         $FailedUsers += $upn
                         Write-Warning "$upn user found, but FAILED to update."
                 }
         }
         else {
                 Write-Warning "$upn not found, skipped"
                 $SkippedUsers += $upn
         }
}

The Date that I am trying to use for the Update:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

UserPrincipalName Department Company
test.nikola@test.local Test 123

The Error message that I get: user found, but FAILED to update

Maybe I am blind but i cant find the error …

>Solution :

As mentioned in the comments, your catch block is hiding all terminating exceptions. Since you never output or inspect the given exception, there’s no way to tell what went wrong.

Change it to:

try {
    $user | Set-ADUser -Department $CSVrecord.Department -Company $CSVrecord.Company -ErrorAction STOP
}
catch {
   $FailedUsers += $upn
   Write-Warning "$upn user found, but FAILED to update: $_"
}

Inside the catch block, $_ will refer to the exception that was caught, so at least you now get a chance to see the underlying error message.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading