如何在 PowerShell 中格式化字符串?


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

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

其次,使用格式方法。在此方法中,我们将使用 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

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

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

更新于:2021 年 1 月 18 日

6K+ 浏览量

开启你的 职业生涯

完成课程并获得认证

开始
广告
© . All rights reserved.