Script failing if not all columns have data to be updated.

MilesLogan
MilesLogan used Ask the Experts™
on
I was helped by an Expert on the script below .. I didn't plan on it but my CSV has blanks on some of the attributes... can someone
assist modifying this so if there is a blank in one of the fields?

so lets say a user only needs 3 of the 4 values below updated , the script below does not work .. it only works if all four fields have values to update.

Import-CSV -Path "$env:SystemDrive\Test\temp.csv" | % {
  Set-ADUser $_.Username -replace @{'msExchExtensionAttribute24' = $_.msExchExtensionAttribute24; 'msExchExtensionAttribute25' = $_.msExchExtensionAttribute25; 'msExchExtensionAttribute26' = $_.msExchExtensionAttribute26; 'msExchExtensionAttribute27' = $_.msExchExtensionAttribute27; }
}

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Jose Gabriel Ortega CastroTop Rated Freelancer on MS Technologies
Awarded 2018
Distinguished Expert 2018

Commented:
Probably somethig like this: (this is not tested)

Import-CSV -Path "$env:SystemDrive\Test\temp.csv" | % {

    $ShouldAdd=@()
    for($i=24; $i-lt 27; $i++){
       $"isNull$i"=  if(!($_."msExchExtensionAttribute$i")){$true}else{$false}
       $ShouldAdd+=$"isNull$i"
    }
    $objects=@{}

    foreach($Sa in $ShouldAdd){
        if($sa){
            $objects+= "'msExchExtensionAttribute$sa' = $_.msExchExtensionAttribute$sa; "
        }
    }

    Set-ADUser $_.Username -replace $objects
    
}

Open in new window

Most Valuable Expert 2018
Distinguished Expert 2018
Commented:
Try it like this:
$attributeList = 'msExchExtensionAttribute24', 'msExchExtensionAttribute25', 'msExchExtensionAttribute26', 'msExchExtensionAttribute27'
Import-Csv -Path "$env:SystemDrive\Test\temp.csv" | ForEach-Object {
	$replace = @{}
	ForEach ($attribute in $attributeList) {
		If ($_.$attribute) {
			$replace[$attribute] = $_.$attribute
		}
	}
	Set-ADUser -Identlity $_.Username -Replace $replace
}

Open in new window

Author

Commented:
Hi oBdA .. that worked exactly as expected and thank you for making the script easy to understand .

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial