I need help adding a exception to my code, I’m imported from csv to update active directory attributes. It works, but I need to put in a exception for example if one of the attributes from the csv is blank or do not have any values " ".

Import-CSV $importfile | ForEach-Object{
     $samaccountname = $_.sAMAccountName.ToLower()
     $department = $_.department
     $phone = $_.Phone
     $emailAddress = $_.emailAddress
     $manager = $_.manager.ToLower()    

Try { 
        $exists = Get-ADUser -LDAPFilter "(sAMAccountName=$samaccountname)" 
        }
    Catch 
    { 
    write-host "Users did not exist."
    }
    If ($exists)
    {
    
        If ($department) 
        { 
            Set-ADUser -Identity $samaccountname -department $department
        }

5 Spice ups
Import-CSV $importfile | ForEach-Object{
    $splat = @{ 'Identity'=$_.sAMAccountName }
    
    If($_.department.Trim()){
        $splat.Add('Department',$_.department)
    }
    If($_.phone.Trim()){
        $splat.Add('OfficePhone',$_.phone)
    }
    If($_.emailaddress.Trim()){
        $splat.Add('EmailAddress',$_.emailaddress)
    }
    If($_.manager.Trim()){
        $splat.Add('Manager',$_.manager)
    }
  
    Set-ADUser @splat
}

This is untested, but that is the general idea.

1 Spice up
ForEach($user in (Import-CSV $importfile)) {
    If(!($user.samaccountname.trim())){
        Continue
    }
    
    $splat = @{ 'Identity'=$user.sAMAccountName.trim() }
    
    If($user.department.Trim()){
        $splat.Add('Department',$user.department.trim())
    }
    If($user.phone.Trim()){
        $splat.Add('OfficePhone',$user.phone.trim())
    }
    If($user.emailaddress.Trim()){
        $splat.Add('EmailAddress',$user.emailaddress.trim())
    }
    If($user.manager.Trim()){
        $splat.Add('Manager',$user.manager.trim())
    }

    If(($splat.keys | Measure-Object).count -ge 2) {
        Set-ADUser @splat
    }
}

Somewhat improved. Still untested.

1 Spice up

I have a script script that does this. Check iTechguides.com and search ‘powershell script to create new AD users from CSV’. As a guide, on your last ‘IF’ statement, you can ignore blank fields like this:

If ($department -ne ‘’)
{
Set-ADUser -Identity $samaccountname -department $department
}

This will only atempt to execute Set-ADUser if department is Not Equal to Null. If the value is null, it will ignore it