how to deal with blank entries in a hash?

This topic contains 3 replies, has 4 voices, and was last updated by  Naw Awn 2 weeks ago.

  • Author
    Posts
  • #81577

    rino19ny
    Participant

    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 = $_.city
        msExchExtensionAttribute20 = $_.zip
        Comment = $_.phone
        msExchExtensionAttribute19 = $_.loc
    }
    
    try {
        Set-ADuser -Identity $_.ID -Replace $hash
    
    }
    catch {
        Write-Output "$_.ID does not exist"
    
    }
    }
    
  • #81586

    Don Jones
    Keymaster

    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) {
      $hash.Add('key','value')
    }
    

    Something vaguely like that.

  • #81589

    Dave Brannan
    Participant

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

  • #81625

    Naw Awn
    Participant

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

You must be logged in to reply to this topic.