none
PowerShell update users RRS feed

  • Question

  • Hello everybody,

    I'm writing a script to update some of the usernames in our Active Directory.

    This is being done by importing a CSV file and then using a 'foreach' loop to go through the entries. Before the script is actually going to update the AD objects, I would like to check if every entry is correct. However it isn't working.. In my CSV file there are some entries that are not present in AD. However it isn't getting returned.

    I would appreciate it alot if someone could point me to what I'm doing wrong!

    $myWindowsID=[System.Security.Principal.WindowsIdentity]::GetCurrent()
    $myWindowsPrincipal=new-object System.Security.Principal.WindowsPrincipal($myWindowsID)
    $adminRole=[System.Security.Principal.WindowsBuiltInRole]::Administrator
    
    if ($myWindowsPrincipal.IsInRole($adminRole))
       {
       $Host.UI.RawUI.WindowTitle = $myInvocation.MyCommand.Definition + "(Elevated)"
       clear-host
       }
    else
       {
       $newProcess = new-object System.Diagnostics.ProcessStartInfo "PowerShell";
       $newProcess.Arguments = $myInvocation.MyCommand.Definition;
       $newProcess.Verb = "runas";
       [System.Diagnostics.Process]::Start($newProcess);
       exit
       }
    
    Import-Module ActiveDirectory
    Write-Host 'Starting to check CSV file...' -ForegroundColor Yellow
    Write-Host
    
    Import-Csv C:\users.csv | ForEach-Object {
        if (Get-ADUser $_.sAMAccountName) {
            Write-Host "Found user: " $_.sAMAccountName
        } Else {
            Write-Host "Unable to find user: " $_.sAMAccountName
            $err = $true
        }
    }
    
    If ($err) {
        Write-Host
        Write-Host "Press any key to continue ..."
        $x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
        Exit
    }
    
    Write-Host 'Starting to update users...' -ForegroundColor Yellow
    Write-Host
    
    $users = Import-Csv C:\users.csv
    foreach ($user in $users) {
        Set-ADUser $user.sAMAccountName -SAMAccountName $user.newSAMAccountName -UserPrincipalName $user.newUPN -verbose
    }
    
    Write-Host
    Write-Host 'Done!' -ForegroundColor Green
    Write-Host "Press any key to continue ..."
    $x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")

    Monday, September 26, 2016 11:56 AM

Answers

  • HINT:

    Import-Csv C:\users.csv | 
    	ForEach-Object {
    		$samname = $_.sAMAccountName
    		if (Get-ADUser -Filter "Name -eq '$samname'") {
    			Write-Host "Found user: $samname"
    		} Else {
    			Write-Host "Unable to find user: $samname"
    		}
    	}


    \_(ツ)_/


    Monday, September 26, 2016 4:20 PM

All replies

  • So, "here's my code dump. Can someone spot that elusive bug for me?"

    This is not a question. This is a "fix my code for me" request.

    What you need to do: Start small. Write a very short script that contains only the absolute minimum amount of code needed to reproduce the problem. Then tell precisely what you were expecting to happen, and what happens instead.

    Also, tell the exact error message(s) -- don't say "it didn't work." You have to say how it didn't work.


    -- Bill Stewart [Bill_Stewart]

    Monday, September 26, 2016 2:17 PM
    Moderator
  • As noted, that is a lot of code to analyze. We need to at least know what line of the script raises an error, and what the error message is.

    Changing sAMAccountNames in bulk can be a big project. There are a lot of things that can go wrong. In the past I wrote a script to modify sAMAccountNames in bulk that checks for all things I know of: uniqueness in the domain, invalid characters, value too long, etc. For uniqueness I retrieve the sAMAccountNames of all objects with this attribute, not just users but also computers and groups, and populate a hash table. That makes it easy to check. I posted my script here:

    https://gallery.technet.microsoft.com/Update-sAMAccountNames-of-7d50f9c2

    This might give you some ideas. The script is written to update sAMAccountName for all users in bulk (or all users in an OU) using a function that determines the new value from existing values, like the givenName and sn (first and last names) of the user. The script could be modified to instead operate on all users in a CSV file. You could either code your own Get-Name function to calculate the new sAMAccountName, or code it to retrieve the new name from the csv. As written the script will append a digit to the new name if there is a conflict with an existing object. The script does all of the necessary checks and writes a detailed log file. The script also can be run to log what it would do, without actually modifying anything. The variable $Update is assigned $False in the script as posted, so it only logs. To actually modify the users you would change this to $True.


    Richard Mueller - MVP Enterprise Mobility (Identity and Access)

    Monday, September 26, 2016 3:32 PM
    Moderator
  • HINT:

    Import-Csv C:\users.csv | 
    	ForEach-Object {
    		$samname = $_.sAMAccountName
    		if (Get-ADUser -Filter "Name -eq '$samname'") {
    			Write-Host "Found user: $samname"
    		} Else {
    			Write-Host "Unable to find user: $samname"
    		}
    	}


    \_(ツ)_/


    Monday, September 26, 2016 4:20 PM
  • This worked! Thanks a lot.

    I'm glad you understood what I meant and found the error :)

    Tuesday, September 27, 2016 10:01 AM
  • That is a really nice way to update the sAMAccountNames in AD via PowerShell. I will definitely inspect it and try to see if I can understand what it does, so that I can incorporate some pieces in my script. The logging especially has my interest. 

    Our AD is quite small and there are only some 50 accounts that need to be changed. So I won't go over the top with the script, I could also just do it by hand, but this a  great chance to familiarize myself with PowerShell.

    Thanks again for pointing out your script!

    Tuesday, September 27, 2016 10:04 AM