在PowerShell中,您可以在字符串中展开变量,如下所示:
$myvar = "hello"
$myvar1 = "$myvar`world" #without the `, powershell would look for a variable called $myvarworld
Write-Host $myvar1 #prints helloworld
我遇到的问题是转发字符,例如n
r等,如下所示:
$myvar3 = "$myvar`albert"
Write-Host $myvar3 #prints hellolbert as `a is an alert
以下也不起作用:
$myvar2 = "$myvar`frank" #doesnt work
Write-Host $myvar2 #prints hellorank.
问题: 当我使用自动变量扩展功能时,如何组合字符串而不必担心转义字符? 或者我必须这样做:
$myvar = "hello"
$myvar1 = "$myvar"+"world" #using +
Write-Host $myvar1
$myvar2 = "$myvar"+"frank" #using +
答案 0 :(得分:20)
这种方式尚未提及:
"$($myvar)frank"
而且:
"${myvar}frank"
答案 1 :(得分:2)
这看起来很糟糕,但作为另一种选择,您可以添加空格和退格:
$myvar = "hello"
$myvar1 = "$myvar `bworld"
$myvar1
答案 2 :(得分:2)
另一种选择是将变量表达式包装在$():
中$myvar3 = "$($myvar)albert"
Write-Host $myvar3
答案 3 :(得分:1)
另一个选择是通过格式运算符:
"{0}world" -f $myvar
答案 4 :(得分:1)
另一个选项是双引号here-string:
$myvar = "Hello"
$myvar2 = @"
$myvar$("frank")
"@