Hash Table Manipulation

Welcome Forums General PowerShell Q&A Hash Table Manipulation

This topic contains 4 replies, has 3 voices, and was last updated by

 
Participant
1 year, 5 months ago.

  • Author
    Posts
  • #80836

    Participant
    Points: 1
    Rank: Member

    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

    Participant
    Points: 251
    Helping Hand
    Rank: Contributor
    $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

    Participant
    Points: 15
    Rank: Member

    Try this Quick and easy way!

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

      Participant
      Points: 251
      Helping Hand
      Rank: Contributor

      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

    Participant
    Points: 1
    Rank: Member

    Hi guys

    Many thanks for your help!

    Naw your solution works perfectly many thanks.

    Baz

The topic ‘Hash Table Manipulation’ is closed to new replies.

denizli escort samsun escort muğla escort ataşehir escort kuşadası escort