Use Set-ADUser command to update user attributes

How to use Set-ADUser command? Updating user properties manually can be time consuming. This is why its good to have a script for bulk modifications. One of the ActiveDirectory module command is called Set-ADUser and it allows us to modify user properties.

Below you can find script for adding or updating AD user mobile phone. To update phone number for one specific user we can just run the following command:

$Number = "+48555666777"
Set-ADUser -Identity Pawel.Janowicz -MobilePhone $Number

#Or

Set-ADUser -Identity Pawel.Janowicz -replace @{ 'MobilePhone' = $($Number) } 

Remember to create CSV file with two columns – “Username” and “Mobile”:

Import-CSV "C:\users\$env:username\Desktop\Users.csv"
CSV
CSV

Final script:

$UsersCSV = Import-CSV "C:\users\$env:username\Desktop\Users.csv"
$Results = @()

ForEach ($User in $UsersCSV) {
    $Username = $User.username.trim() 
    $Number = $User.mobile.trim()
    $UserDetails = $null
    $UserCheck = $null

    Try{
        $UserDetails = Get-ADUser -Identity $Username -Properties MobilePhone
    }
    Catch{
        $_.Exception.Message
        Continue
    }

    If (!$UserDetails.'MobilePhone') {
        Try{
            Set-ADUser -Identity $username -replace @{ 'MobilePhone' = $($Number) } 
            $UserCheck = Get-ADUser -Identity $Username -Properties mobilephone -ErrorAction Stop
            If ($UserCheck) {
                $Object = New-Object PSObject -Property ([ordered]@{ 
    
                    "User name"               = $Username
                    "Mobile"                  = $UserCheck.MobilePhone        
                })
 
                $Results += $Object 
            }
        }
        Catch{
            $_.Exception.Message
            Continue
        }
    }      
}

$Results | Format-Table

In previous articles you can find information about getting user properties – link.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.