I have a simple script

Import-module ActiveDirectory
$users = import-csv "C:\ad_import\users.csv"
foreach ($user in $users) {
set-aduser -identity $user.samaccountname -givenName $user.FirstName -surname $user.LastName -title $user.JobTitle -description $user.description -state $user.State -Office $user.Office -department $user.Department -city $user.City -manager $user.manager -company $user.company

}

It happens that some existing values in AD needs to be cleared for some users, so if I left a cell blank in the csv file I receive an error related to -replace parameter. I tried a lot but couldn’t fix it.

3 Spice ups

Not tested

Import-module ActiveDirectory
$users = Import-Csv "C:\ad_import\users.csv"
foreach ($user in $users) {
    $props = @{
        identity    = $user.samaccountname
        givenName   = if($user.FirstName  ){$user.FirstName  }else{$null}
        surname     = if($user.LastName   ){$user.LastName   }else{$null}
        title       = if($user.JobTitle   ){$user.JobTitle   }else{$null}
        description = if($user.description){$user.description}else{$null}
        state       = if($user.State      ){$user.State      }else{$null}
        Office      = if($user.Office     ){$user.Office     }else{$null}
        department  = if($user.Department ){$user.Department }else{$null}
        city        = if($user.City       ){$user.City       }else{$null}
        manager     = if($user.manager    ){$user.manager    }else{$null}
        company     = if($user.company    ){$user.company    }else{$null}
    }
    set-aduser @props
}

1 Spice up

Hi JitenSh,

Maybe I wasn’t able to explain my requirements properly but I actually have some columns in the csv file has values for some users and empty for others, the empty values needs to clear an existing AD values if it does have value. so for example if I set -state $null that will clear State AD field for all users.

empty value doesn’t mean anything,I didn’t say about all users only those users whom you want to clear some fields.

samaccountname,title,department
john, teamlead,IT
Nedd,accountnant,$null

Unfortunately that wouldn’t help in my case because it’s an automated process and the csv file i receive from HR system in a specified share folder, and I have a scheduled task for the script runs daily. Thanks for your help anyway :slight_smile:

Tested and works fine with me. Thanks a lot :slight_smile: