Hash Table Manipulation

This topic contains 4 replies, has 3 voices, and was last updated by  Barry Walledge 2 weeks, 6 days ago.

  • Author
    Posts
  • #80836

    Barry Walledge
    Participant

    Hi all

    Not sure if you can help me please?

    I have a hash table in the following format, which is dynamically created:

    $standardADParm = @{"city" = $city
    "EmployeeID" = $employeeID
    "Fax" = $fax
    "givenname" = $givenName
    "MobilePhone" = $mobilePhone
    "OfficePhone" = $officePhone
    "PostalCode" = $postalCode
    "State" = $state
    "StreetAddress" = $streetAddress
    "surname" = $surname
    "Title" = $title
    }

    How to I remove items that are blank as I'm then splatting this into a set-aduser and as you know any blank items will cause an issue. eg how do I check for blank values and then remove the corresponding key?

    Thanks

    Baz

  • #80840

    Sam Boutros
    Participant
    $city      = 'New York'
    $givenName = 'Sam'
    
    $standardADParm = @{
        city          = $city
        EmployeeID    = $employeeID
        Fax           = $fax
        givenname     = $givenName
        MobilePhone   = $mobilePhone
        OfficePhone   = $officePhone
        PostalCode    = $postalCode
        State         = $state
        StreetAddress = $streetAddress
        surname       = $surname
        Title         = $title
    }
    
    $NonBlankKeys = $standardADParm.GetEnumerator().Name | ? { $standardADParm.$_ }
    
    if ($NonBlankKeys) {
        $Prop1 = $NonBlankKeys | select -First 1
        $newADParam = @{ $Prop1 = (Get-Variable $Prop1).Value }
        if ($NonBlankKeys.count -gt 1) {
            1..($NonBlankKeys.count-1) | % {
                 $newADParam.Add($NonBlankKeys[$_],(Get-Variable $NonBlankKeys[$_]).Value)
            }
        }
        $newADParam
    }
    
  • #80842

    Naw Awn
    Participant

    Try this Quick and easy way!

    [String[]]$keys = $standardADParm.GetEnumerator().Name
    
    foreach($kee in $keys){
        If ($standardADParm.Item("$kee") -eq ""){$standardADParm.Remove("$kee")}   
    }
    
    • #80845

      Sam Boutros
      Participant

      nice Awn!

      $standardADParm.GetEnumerator().Name | % {
          If (!$standardADParm.Item($_)){ $standardADParm.Remove($_) }   
      }
      

      So Barry, simply use the GetEnumerator method to list the hash table keys, and the Remove method to weed out those with blank values..

  • #80851

    Barry Walledge
    Participant

    Hi guys

    Many thanks for your help!

    Naw your solution works perfectly many thanks.

    Baz

You must be logged in to reply to this topic.