How to use string.format with a string array in powershell

I want to output a formatted string to the console. I have one string variable and one string array variable.

When I do this:

$arr = "aaa","bbb"
"test {0} + {1}" -f "first",$arr

Conclusion:

test first + System.Object[]

But I need a conclusion:

test first + aaa,bbb

Or something similar...

+5
source share
1 answer

Several parameters:

  • Join the array first, so you don't rely on the default implementation ToString()(which just prints the class name):

    PS> 'test {0} + {1}' -f 'first',($arr -join ',')
    test first + aaa,bbb
    
  • Use string interpolation:

    PS> $first = 'first'
    PS> "test $first + $arr"
    test first + aaa bbb
    

    You can change the separator used by the installation $OFS, which is the default space:

    PS> $OFS = ','
    PS> "test $first + $arr"
    test first + aaa,bbb
    
  • You can get the same result (including note about $OFS) with

    PS> 'test {0} + {1}' -f 'first',(''+$arr)
    test first + aaa bbb
    

    This makes the array also convert to a single string.

+12
source

All Articles