Quantcast
Channel: PowerShell.com – PowerShell Scripts, Tips, Forums, and Resources
Viewing all articles
Browse latest Browse all 6937

Updating ADusers from CSV

$
0
0

I got this script working the way I wanted, here's final version:

clear
$users = Import-CSV "C:\x.csv" -delim ';' -encoding UTF8
$ou = Read-Host 'Which OU to update'
Foreach ($user in $users) { 
    if ($user.'SamAccountName') {
  $aduser = Get-ADUser -Filter "SamAccountName -eq '$($user.samaccountname)'" -SearchBase "OU=$ou,OU=ENEA-SERWIS,DC=enea,DC=pl"
  }
    if ($aduser) {
  Write-Host "Updating active directory user: " -nonewline; Write-Host $aduser.name -ForegroundColor Yellow
   $userprops = Get-Member -InputObject $user -MemberType NoteProperty
  Foreach ($userprop in $userprops) {
   $propname = $userprop.name
   $propvalue = $userprop.Definition.Split("=")[1]
   if ($propvalue) { if ($aduser.$userprop -eq "") -or ($aduser.$userprop -eq $null) {
           #splat the values into a parameters hashtable
           $parms = @{$propname = $propvalue}
           Set-ADUser $aduser @parms}
           }
   } else {
    Write-Host "Property " -nonewline; Write-Host $propname -ForegroundColor Magenta -nonewline; Write-Host " was empty for user " $user.SamAccountName " - AD User property not changed"
   }
  }
 } else {
  Write-Host "Couldn't find a user in active directory to match CSV User:"  $user.SamAccountName
 }
 #Clear the aduser variable in case we don't find one next time round.
 Clear-Variable aduser
}


 

Now... I messed it up a bit :) There is a small catch, I was told about later on (to late, and got bit messy). I only had to update EMPTY AD fields. If there is any value set to some user field/attribute it should be left as it is, even if in CSV file it's different. I replaced AD values with those from CSV and some applications stopped working - they need specific values in some fields, even if they dont make sense. So only updating empty ones.

So, my plan was to just add extra IF condition, and check if given field is $null or "", but it doesn't work like it should. I bet there's just a small detail I'm missing, which prevents it from doing what it should do. It doesn't give me any error, but also doesn't update like it should.

Above is working script which updates all users, checks for empty fields in CSV file. But I need extra check to it. I've added in bold an extra condition I thought will be enough. But seems like that $aduser.$userprop is completely wrong, unsure how to handle it..

I'm real just a beginner with scripts and Powershell in general, but got this silly assignement to update 400+ accounts and thought I'll spend even few days doing it right (via script) instead brutal forcing tchem all one by one. But I got problems with basic concepts of scripting sometimes and it's hard for me to figure out how to fix my mistake.

Please.. help ?


Viewing all articles
Browse latest Browse all 6937

Trending Articles