How to check csv for blank fields when updating AD from a CSV file

how to simply update my script to check if a field in the csv  file is blank or not with out having to rewrite the entire script.

The script works perfectly untill it sees a a blank field. it will error our.

 


# Import AD Module            
Import-Module ActiveDirectory           

write-Host 'Starting to update AD Attributes.......' -NoNewline -ForegroundColor Yellow           
# Import CSV into variable $users          
     
$users = Import-Csv -Delimiter "," -Path C:\temp\Users.csv           
# Loop through CSV and update users if the exist in CVS file           
           
foreach ($user in $users) {           
#Search in specified OU and Update existing attributes           
 Get-ADUser -Filter "samaccountname -eq '$($user.samaccountname)'" -Properties * -SearchBase "DC=corp,DC=fishing,DC=com"|           
  Set-ADUser -GivenName $($user.Firstname) -Surname $($user.Lastname) -DisplayName $($user.DisplayName) -Title $($user.JobTitle) -MobilePhone $($user.MobilePhone) -OfficePhone $($user.OfficePhone) -Street $($user.Street) -City $($user.City) -State $($user.State) -PostalCode $($user.PostalCode) -EmailAddress $($user.EmailAddress) -Department $($user.Department) -Office $($user.Office) -Manager $($user.Manager) -Company $($user.Company) -Country $($user.Country) -Description $($user.Description)
       
}

Write-Host 'done!' -ForegroundColor Green

Parents
No Data
Reply
  • I was having the same exact problem.  I ended up running multiple Get|Set-ADUser to overcome the issue... probably not the best way but I have no idea how to do if() statements all on one line.

    Here is an example for two properties... you would need to do the same for all properties as needed. FYI some properties need to be emptied using  -Clear instead of setting $null

    if($user.samaccountname){   #to prevent line errors of missing account name..


        if($user.Firstname){
            Get-ADUser -Filter "samaccountname -eq '$($user.samaccountname)'" -Properties * -SearchBase "DC=corp,DC=fishing,DC=com"|
            Set-ADUser -GivenName $($user.Firstname)
        }else{
            #this will set as null if blank... you may not want this behaviour.
            Get-ADUser -Filter "samaccountname -eq '$($user.samaccountname)'" -Properties * -SearchBase "DC=corp,DC=fishing,DC=com"|
            Set-ADUser -GivenName $null
        }

        if($user.Lastname){
            Get-ADUser -Filter "samaccountname -eq '$($user.samaccountname)'" -Properties * -SearchBase "DC=corp,DC=fishing,DC=com"|
            Set-ADUser -Surname $($user.Lastname)
        }else{
            #this will set as null if blank... you may not want this behaviour.
            Get-ADUser -Filter "samaccountname -eq '$($user.samaccountname)'" -Properties * -SearchBase "DC=corp,DC=fishing,DC=com"|
            Set-ADUser -Surname $null
        }


    }

Children
No Data