Powershell to update AD

asked 2021-11-12T05:44:51.12+00:00
Sashank Singh 26 Reputation points

Hi Gurus,

I need some help with updating AD attribute - Telephonenumber and Mobile by feeding CSV file with help of Samaccount name , My csv consist of below

samaccountname,telephonenumber,Mobile

some of the field for some samaccount could be null

What i want to achieve is i want my PS to import the csv and update the ad attribute according to the csv. If the value is not present in CSV i want my AD attribute to be cleared and if it already exist i want it to be overriden by whatever the value is.

So far i have come up with this PS

    $userstoupdate = import-csv -path "C:\temp\something.csv"
    foreach($User in $Userstoupdate)
    {
    Set-ADuser -Identity $User.samaccountname -MobilePhone $user.mobile}

the above only updates mobile, i want someone to guide to have that shell to update both telphone number and mobile and if the value in CSV file is empty clear the attribute value in AD

Regards,

Active Directory
Active Directory
A set of directory-based technologies included in Windows Server.
3,604 questions
No comments
{count} votes

Accepted answer
  1. answered 2021-11-14T11:11:36.79+00:00
    Clément BETACORNE 2,011 Reputation points

    Hello,

    Below an example of what you need :

    $CSVFile = Import-Csv -Path "C:\temp\Temp - sashank\testph.csv" -Delimiter ","
    $colObjUser = @()
    
    foreach($line in $CSVFile) {
        try {
            $user = Get-ADUser -Identity $line.samaccountname -ErrorAction Stop
        }
        catch {
            $boolModified = $false
            $status = "Cannot find user"
            $user = $null
        }
    
        if($line.Mobile -eq "") {
            $mobile = $null
        } else {
            $mobile = $line.Mobile
        }
    
        if($line.telephonenumber -eq "") {
            $telephone = $null
        } else {
            $telephone = $line.telephonenumber
        }
    
        if($user -ne $null) {
            try {
                $status = ""
                Set-ADUser -Identity $user.SamAccountName -OfficePhone $telephone -MobilePhone $mobile -ErrorAction Stop
                $boolModified = $true
            }
            catch {
                $boolModified = $false
                $status = "Cannot modify user"
            }
        }
        $hash = @{
            samaccountname = $line.samaccountname
            telephonenumber = $line.telephonenumber
            mobile = $line.Mobile
            modified = $boolModified
            status = $status
        }
        $objUser = New-Object PSObject -Property $hash
        $colObjUser = $colObjUser + $objUser
    }
    
    Write-Output $colObjUser
    

0 additional answers

Sort by: Most helpful