locked
Powershell - Creating hashtable from arrays RRS feed

  • Question

  • Howdy,

    I am working on a script, and I have ended up with two arrays like so:

    $servers = @("ServerX","ServerY")

    $reportID = @(123456,098765)

    Given the two simple arrays above, how would I combine into a single hashtable where the servers are the key, and the reportID is the value?

    Key, Value

    Server X, 123456

    Server Y,  098765

    Thank you!!


    • Edited by JscoLP Thursday, October 2, 2014 1:32 AM
    Thursday, October 2, 2014 1:30 AM

Answers

  • Here's one way:


    $servers = "ServerX","ServerY"
    $reportIDs = 123456,098765
    $hash = @{}
    for ( $n = 0; $n -lt $servers.Count; $n++ ) {
      $hash.Add($servers[$n], $reportIDs[$n])
    }
    


    -- Bill Stewart [Bill_Stewart]

    • Marked as answer by Bill_Stewart Monday, November 3, 2014 9:47 PM
    Thursday, October 2, 2014 2:03 AM

All replies

  • Here's one way:


    $servers = "ServerX","ServerY"
    $reportIDs = 123456,098765
    $hash = @{}
    for ( $n = 0; $n -lt $servers.Count; $n++ ) {
      $hash.Add($servers[$n], $reportIDs[$n])
    }
    


    -- Bill Stewart [Bill_Stewart]

    • Marked as answer by Bill_Stewart Monday, November 3, 2014 9:47 PM
    Thursday, October 2, 2014 2:03 AM
  • Thanks Bill, that is slick!
    Thursday, October 2, 2014 2:23 AM
  • Here's another:

    $servers = @("ServerX","ServerY")
    $reportID = @(123456,098765)
    
    $ht=@{}
    
    $servers | 
    foreach { $i=0 } { $ht[$_] = $reportID[$i++] } {} 
    
    $ht 
    
    Name                           Value                                                         
    ----                           -----                                                         
    ServerX                        123456                                                        
    ServerY                        98765                                                         


    [string](0..33|%{[char][int](46+("686552495351636652556262185355647068516270555358646562655775 0645570").substring(($_*2),2))})-replace " "

    Thursday, October 2, 2014 3:08 AM
  • One more? :)

    $servers = "ServerX","ServerY"
    $reportIDs = 123456,098765
    $ht = @{}
    Invoke-expression ('$ht.'+"$($servers -join ',$ht.') = $( $reportIDs -join ',')")
    $ht

    But, still prefer the above examples with for/foreach loop by Bill and mkolinor.

    • Edited by Neothwin Thursday, October 2, 2014 8:24 AM
    Thursday, October 2, 2014 8:00 AM