Set-ADUser - CSV import with empty fields


I’m making changes to AD with information from a CSV file, sometimes fields are empty on some users, could be telephone number, and that translate to that they should be empty in AD as well. How would i do that?

Right now i get an error for each empty field…

$users = Import-CSV -Delimiter ";" -Path c:\pathtocsv.csv
ForEach($User in $Users){
$ADUser = Get-ADUser -Identity $($User.SamAccountName) -Properties *
 if ($ADUser){
        Set-ADUser -Identity $ADUser `
        -Country $User.Country `
        -Department $User.Department `
        -OfficePhone $User.OfficePhone `
        -StreetAddress $User.Address `
        -City $User.City `
        -State $User.State `
        -PostalCode $User.PostalCode `
        -Mobile $User.MobilePhone `
        -Office $User.Office `

        Write-Warning ("Failed to update " + $($User.SamAccountName))

You will need to check beforehand if the cell is empty and omit the parameter to set the property you don’t have a value for.

Regardless of that you shouldn’t use backticks as line continuation characters as they are considered very bad style and quite error prone. Instead you should use splatting. That would simplify the task of adding parameters on a case-by-case basis since you can easily add key value pairs with if statements to a hashtable.

1 Like