PowerShell 中的字符串格式化是如何工作的?

powershellmicrosoft technologiessoftware & coding更新于 2026/2/9 23:22:17

要在 PowerShell 中格式化字符串,可以使用 -F 运算符。使用 -F 格式时,需要在花括号中提供参数编号。

示例

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

对于多个值,

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

从上面的例子,我们了解到,如果需要使用 -F 运算符获取多个变量的输出,那么我们可以递增大括号中的数字。

要使用 Write-Output 命令获取上述输出,

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

如果我们使用上述方法,输出将会混乱,因此为了获得正确的格式,我们需要在 Write-Output 中使用圆括号,如下所示。

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

相关文章