8

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...

1 Answer 1

14

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Very nice! I would normally use string interpolation right away, but I just discovered -f operator for string.format and liked it so much I used it everywhere and got confused :) This raises another question what is the difference in background processing of -f operator and string interpolation? Maybe some articles? Thanks
-f is just a straightforward convenience for String.Format(), it uses the same semantics as .NET in that regard. String interpolation is a tricky subject, as it converts objects to string using the invariant culture (apparently); it will also join arrays using $OFS. Generally I don't feel confident right now to accurately summarise the exact differences. Something fun: $a = (date),(date),(date); Write-Host $a; Write-Host "$a"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.