How does string formatting work in PowerShell?

PowerShellMicrosoft TechnologiesSoftware & Coding

To format string in PowerShell, you can use -F operator. When you use -F format, you need to provide the argument number in the curly brackets.


PS C:\> $Str = "Hello PowerShell"
PS C:\> "{0}" -f $str
Hello PowerShell

For the multiple values,

PS C:\> $Str = "Hello PowerShell"
PS C:\> $str1 = "Rockstart"
PS C:\> "{0} says {1}" -f $Str,$str1
Hello PowerShell says Rockstart

From the above example, we understood if we need to get the output for multiple variables using the -F operator then we can increment the number in curly brackets.

To use the above output with the Write-Output command,

PS C:\> Write-Output "{0} says {1}" -f $str,$str1
{0} says {1}
Hello PowerShell

If we use the above method, the output will be messed up so to get the output in the correct format, we need to use the round bracket with Write-Output as shown below.

PS C:\> Write-Output ("{0} says {1}" -f $str,$str1)
Hello PowerShell says Rockstart
Updated on 09-Nov-2020 09:46:56