如何在 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+ 瀏覽量

開啟你的 職業生涯

完成課程並獲得認證

開始
廣告