PowerTip: A Couple Quick PowerShell Array Tricks

PowerTip: A Couple Quick PowerShell Array Tricks

  • Comments 7
  • Likes

Summary:  Learn some quick tricks for using Windows PowerShell arrays.

Hey, Scripting Guy! Question How can I split the following string in the $a variable?

$a = "atl-ws-01,atl-ws-02,atl-ws-03,atl-ws-04"

Hey, Scripting Guy! Answer Use the split method :

$b = $a.split(",")


Hey, Scripting Guy! Question How do I join an array, such as the one in the $a variable shown here?

 $a = "h","e","l","l","o"

Hey, Scripting Guy! Answer Use the join static method from the string c

Your comment has been posted.   Close
Thank you, your comment requires moderation so it may take a while to appear.   Close
Leave a Comment
  • i dont get the second part,

    How do I join an array, such as the one in the $a variable shown here?

    $a = "h","e","l","l","o"

    Use the join static method from the string c.

    where i put the join?

  • @Matheus Kamphorst  here is one way . . using the join operator. (there is also the split operator).

    # Join

    $a = "h","e","l","l","o"

    $a -join "-"

    > h-e-l-l-o

    # Split

    $a = "atl-ws-01,atl-ws-02,atl-ws-03,atl-ws-04"

    $a -split ","

    > atl-ws-01

    > atl-ws-02

    > atl-ws-03

    > atl-ws-04

    # Info under help topic

    help about_operators

    Another real life example is:

    $ENV:PSModulePath -split ";"

    > C:\Users\administrator\Documents\WindowsPowerShell\Modules

    > C:\windows\system32\WindowsPowerShell\v1.0\Modules\

  • @Matheus: I don't know exactly what Ed means, but ....

    You could use the [string] type (class) to see which static members if offers:

    [string] | get-member -static

    The "join" method is listed now.

    If you want to know more about that method type: [string]::Join

    And you can guess the meaning of the parameters now!

    If you use the signature:

    static string Join(string separator, Params string[] value)

    this should work:  [string]::Join("",$a)


    Here we used an empty seperator, but you can use any string you like!

    I hope it helps


  • @Matheus Kamphorst

    PS C:\> $a = "h","e","l","l","o"

    PS C:\> [string]::join("",$a)


    @Ben Wilkinson,  @K_Schulte Thanks :-)

  • Hi,

    here is also:

    PS II>  $a = "h","e","l","l","o"

    PS II> $_OFS=$OFS ; $OFS=[string]::Empty

    PS II> "$a"


    PS II> # or

    PS II> -join $a


    PS II> # or

    PS II> [string]::Concat($a)


    PS II> $a = "atl-ws-01,atl-ws-02,atl-ws-03,atl-ws-04"

    PS II> $a -replace ',',"`r`n"





  • $c = "h","e","l","l","o"


  • In about_join it shows the -join unary operator.

    $z = "a", "b", "c"

    -join $z