Set-ADUser based on .csv file - empty attributes issue

Hi, after a few months without working with PowerShell my knowledge is slowly fading away but fortunately every time this happened before, I was able to rebuild my knowledge again and now it is the same story. However I want to optimize my simple code which populates three AD user object attributes: manager, officephone and fax with values stored in .csv file. Everything works well, but my code looks not so good in my opinion. Is there any more elegant solution?

$AddressBook = Import-CSV -Path D:\AddressBookFinal.csv

foreach($Employee in $AddressBook)

{

     if([string]::IsNullOrEmpty($Employee.ManagerUserName)) {

              Set-ADUser -Identity $Employee.EmployeeUserName -Manager $null

    } else {

              Set-ADUser -Identity $Employee.EmployeeUserName -Manager $Employee.ManagerUserName

    }

    <#similar code here for checking value of OfficePhone and Fax attributes and populating             AD attributes depending on if attribute value in .csv file is empty or not#> 

}











  • Edited by BoxiKG 16 hours 40 minutes ago
February 9th, 2015 8:26am

This should work, I'm pretty sure you can give it null values.

$AddressBook = Import-CSV -Path D:\AddressBookFinal.csv

foreach($Employee in $AddressBook) {


set-aduser -Identity $employee.EmployeeUserName -Replace @{Manager = $Employee.ManagerUserName
                                          telephoneNumber = $employee.OfficePhone
                                          facsimileTelephoneNumber = $employee.FaxNumber}




}

Free Windows Admin Tool Kit Click here and download it now
February 9th, 2015 9:55am

No sure if this would help or just rearrange things, but you could build a hash table of the attributes you want to change and execute just one Set-AdUser command.

$HashTable = @{attribute1=value1;attribute2=value2}

Set-ADUser Identity $Employee.EmployeeUserName -Replace $HashTable

February 9th, 2015 9:58am

Your code looks good to me.

A minor point. When you assign $Null to a PowerShell AD parameter, like Manager, under the covers the cmdlet invokes Clear to clear the underlying manager attribute. Technically, you cannot assign blank or null to any AD attribute. The code works, but I always need to check when I see $Null assigned, and remind myself that PowerShell deals with this correctly. I would prefer:

Set-ADUser -Identity $Employee.EmployeeUserName -Clear Manager

But it is a personal preference.
Free Windows Admin Tool Kit Click here and download it now
February 9th, 2015 10:00am

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics