Author Posts

October 9, 2017 at 11:17 am

i'm updating my AD users attributes by reading in from an Excel CSV file. the CSV file most of the times have all column entries filled in but there are times where an entry is empty. this is where my script would give an error and will not save or write the hash table.

for example, in the code below if the title is empty (as read from the CSV file), it would throw and error saying that the "Replace.ID does not exist" (caught by the try/catch statement).

so i'm wondering how to deal with such situation so that the current record for the AD user would still get updated?

if (-not (Get-Module ActiveDirectory)){
	Import-Module ActiveDirectory -ErrorAction Stop            

Import-CSV 'X:\OneDrive\test.csv' | foreach-object {

$hash = @{
	givenName = $_.fname
	sn = $_.lname
	company = $_.comp
	title = $_.title
    department = $_.func
    physicalDeliveryOfficeName = $_.dept
    msExchExtensionAttribute17 = $_.address
    msExchExtensionAttribute18 = $
    msExchExtensionAttribute20 = $
    Comment = $
    msExchExtensionAttribute19 = $_.loc

try {
    Set-ADuser -Identity $_.ID -Replace $hash

catch {
    Write-Output "$_.ID does not exist"


October 9, 2017 at 1:48 pm

You'd need to write an If statement for each one that might be empty, and only add the key to the hash table if there's an associated value.

If ($whatever) {

Something vaguely like that.

October 9, 2017 at 1:49 pm

Personally, I would validate the contents of the csv before doing the foreach and constructing each hash.

October 9, 2017 at 5:17 pm

I think this one has a similar scenario. Check it out.

Hash Table Manipulation