Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use string.format with string array in powershell

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

When I do this:

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

The output is this:

test first + System.Object[]

But I need output to be:

test first + aaa,bbb

Or something similar...

like image 507
jumbo Avatar asked May 16 '12 10:05

jumbo


People also ask

How do I use an array of strings in PowerShell?

To work with an array of strings in PowerShell, firstly, we have to create them. By using the “[String[]]” method, we will create a “$var” array of strings. This “$var” array of strings will contain the values: “PowerShell”, “String”, and “Array”.

How do I add a string to an array in PowerShell?

The + operator in PowerShell is used to add items to various lists or to concatenate strings together. To add an item to an array, we can have PowerShell list all items in the array by just typing out its variable, then including + <AnotherItemName> behind it.

How do I format a string in PowerShell?

To format a string in a PowerShell we can use various methods. First using the simple expanding string method. PS C:\> $str = 'PowerShell' PS C:\> Write-Output "Hello $str !!!!" Hello PowerShell !!!! Second, using the format method.

How do I read an array in PowerShell?

Retrieve items from an ArrayTo retrieve an element, specify its number, PowerShell automatically numbers the array elements starting at 0. Think of the index number as being an offset from the staring element. so $myArray[1,2+4.. 9] will return the elements at indices 1 and 2 and then 4 through 9 inclusive.


1 Answers

Several options:

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

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

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

    You can change the delimiter used by setting $OFS, which by default is a space:

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

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

    This forces the array to be converted into a single string first, too.

like image 96
Joey Avatar answered Nov 12 '22 02:11

Joey