我正在尝试在字符串中连接变量。
代码:
$uniqueID = "123"
$Key = '<add key="uniqueID" value="$uniqueID" />'
write-host $Key
Run Code Online (Sandbox Code Playgroud)
结果我想要:
<add key="uniqueID" value="123" />
Run Code Online (Sandbox Code Playgroud)
结果我得到:
<add key="uniqueID" value="$uniqueID" />
Run Code Online (Sandbox Code Playgroud)
尝试这个 -
$Key = "<add key=`"uniqueID`" value=`"$($uniqueID)`" />"
Run Code Online (Sandbox Code Playgroud)
要么
$Key = "<add key=`"uniqueID`" value=`"$uniqueID`" />"
Run Code Online (Sandbox Code Playgroud)
若要强制Windows PowerShell从字面上解释双引号,请使用反引号字符。这样可以防止Windows PowerShell将引号解释为字符串定界符。
信息-
如果您看一下Get-Help about_Quoting_Rules,它会说:
SINGLE AND DOUBLE-QUOTED STRINGS
When you enclose a string in double quotation marks (a double-quoted
string), variable names that are preceded by a dollar sign ($) are
replaced with the variable's value before the string is passed to the
command for processing.
For example:
$i = 5
"The value of $i is $i."
The output of this command is:
The value of 5 is 5.
Also, in a double-quoted string, expressions are evaluated, and the
result is inserted in the string. For example:
"The value of $(2+3) is 5."
The output of this command is:
The value of 5 is 5.
When you enclose a string in single-quotation marks (a single-quoted
string), the string is passed to the command exactly as you type it.
No substitution is performed. For example:
$i = 5
'The value of $i is $i.'
The output of this command is:
The value $i is $i.
Similarly, expressions in single-quoted strings are not evaluated. They
are interpreted as literals. For example:
'The value of $(2+3) is 5.'
The output of this command is:
The value of $(2+3) is 5.
Run Code Online (Sandbox Code Playgroud)
您的代码未评估值的原因是因为您使用单引号将变量包装起来$key。用双引号将其包装,然后使用子表达式运算符($($UniqueID)和反引号可以解决问题,或者仅使用$UniqueIDwill也足够。
| 归档时间: |
|
| 查看次数: |
8605 次 |
| 最近记录: |