如何使用 PowerShell 格式化字符串?

powershellmicrosoft technologiessoftware & coding

在 PowerShell 中格式化字符串,我们可以使用多种方法。首先使用简单的扩展字符串方法。

PS C:\> $str = 'PowerShell'
PS C:\> Write-Output "Hello $str !!!!"
Hello PowerShell !!!!

其次,使用 format 方法。在此方法中,我们将使用 String .NET 类的 Format 函数。

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

第三种方法是使用 Format 运算符。我们可以在此处使用数字格式,如下所示。

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

如果有多个变量,则需要增加大括号内的数字。例如:

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

您也可以在 format 方法中使用相同的格式运算符。

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

相关文章