简体   繁体   English

变量扩展和转义字符

[英]Variable expansion and escaped characters

In PowerShell, you can expand variables within strings as shown below:在 PowerShell 中,您可以在字符串中展开变量,如下所示:

$myvar = "hello"
$myvar1 = "$myvar`world" #without the `, powershell would look for a variable called $myvarworld
Write-Host $myvar1 #prints helloworld

The problem I am having is with escaped characters like n r etc, as shown below:我遇到的问题是转义字符,例如n r 等,如下所示:

$myvar3 = "$myvar`albert"
Write-Host $myvar3 #prints hellolbert as `a is an alert 

also the following doesnt work:以下也不起作用:

$myvar2 = "$myvar`frank" #doesnt work
Write-Host $myvar2 #prints hellorank.

Question: How do I combine the strings without worrying about escaped characters when I am using the automatic variable expansion featurie?问题:当我使用自动变量扩展功能时,如何组合字符串而不用担心转义字符? Or do I have to do it only this way:还是我必须这样做:

$myvar = "hello"
$myvar1 = "$myvar"+"world" #using +
Write-Host $myvar1
$myvar2 = "$myvar"+"frank" #using +

This way is not yet mentioned:这种方式还没有提到:

"$($myvar)frank"

And this:和这个:

"${myvar}frank"

This seems kind of kludgy, but as another option, you can add a space and a backspace:这看起来有点笨拙,但作为另一种选择,您可以添加空格和退格:

$myvar = "hello"
$myvar1 = "$myvar `bworld"
$myvar1

Yet another option is to wrap your variable expression in a $():另一种选择是将变量表达式包装在 $() 中:

$myvar3 = "$($myvar)albert"
Write-Host $myvar3 

One other option is through the format operator:另一种选择是通过格式运算符:

"{0}world" -f $myvar

Another option is a double-quoted here-string:另一种选择是双引号的此处字符串:

$myvar = "Hello"
$myvar2 = @"
$myvar$("frank")
"@

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM