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...
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”.
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.
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.
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.
Several options:
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
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With