How to format string using 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. In this method, we will use the Format function of the String .NET class.

PS C:\> $str = "PowerShell"
PS C:\> [String]::Format("Hello $str...!!!")
Hello PowerShell...!!!

The third method using the Format operator. We can use the number format here as shown below.

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

If we have multiple variables then we need to increase the numbers inside the curly brackets. For example,

PS C:\> $str = "PowerShell"
PS C:\> $str1 = "Azure"
PS C:\> "Hello {0} and {1}" -f $str,$str1
Hello PowerShell and Azure

You can also use the same format operator inside the format method.

PS C:\> [String]::Format("Hello {0} and {1}", $str,$str1)
Hello PowerShell and Azure

Updated on: 18-Jan-2021

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements