none
joining list with "," in powershell variable RRS feed

  • Question

  • I have two variable $server, $type, which both have the same amount of lines, I want to join them with a ',' delimiter. I'm struggling to use the correct combination or foreach and interation. below is examples of the output data and my code I've tried. I think I need a -join but I'm struggling to get it to work correct. How do I join these to variable to get my desired result below?

    Example outputs from variables:

    $server ------- server1 server2 $type ------ windows dnmp

    Example code I've tried recently:

    $agentserver = foreach($i in $server){foreach($j in $type){$i + ($j++)}}

    Output I'm trying to get:

    server1,windows

    server2,ndmp


    Sunday, November 18, 2018 4:13 PM

Answers

  • Assuming both arrays are the same length:

    for($i = 0; $i -lt $server.Count){
        '{0},{1}' -f $server[$i],$type[$i]
    }
    


    \_(ツ)_/

    • Marked as answer by inthemix1973 Sunday, November 18, 2018 5:14 PM
    Sunday, November 18, 2018 4:22 PM

All replies

  • If you really have two separate arrays, here's one way you can create a new custom object that combines them:


    $server = "server1","server2"
    $type = "windows","dnmp"
    
    for ( $i = 0; $i -lt $server.Count; $i++ ) {
      [PSCustomObject] @{
        "ServerName" = $server[$i]
        "ServerType" = $type[$i]
      }
    }
    

    This type of data is much more efficiently expressed in a hashtable, though.


    PS C:\> help about_Hash_Tables


    -- Bill Stewart [Bill_Stewart]

    Sunday, November 18, 2018 4:19 PM
    Moderator
  • Assuming both arrays are the same length:

    for($i = 0; $i -lt $server.Count){
        '{0},{1}' -f $server[$i],$type[$i]
    }
    


    \_(ツ)_/

    • Marked as answer by inthemix1973 Sunday, November 18, 2018 5:14 PM
    Sunday, November 18, 2018 4:22 PM
  • Thanks Bill, I will research hash tables more.
    Monday, November 19, 2018 12:49 PM