gpt4 book ai didi

powershell - 在 powershell 中连接字符串内的变量

转载 作者:行者123 更新时间:2023-12-03 00:33:50 31 4
gpt4 key购买 nike

我正在尝试连接字符串中的变量。

代码:

$uniqueID = "123"
$Key = '<add key="uniqueID" value="$uniqueID" />'
write-host $Key

我想要的结果:

<add key="uniqueID" value="123" />

我得到的结果:

<add key="uniqueID" value="$uniqueID" />

最佳答案

试试这个 -

$Key = "<add key=`"uniqueID`" value=`"$($uniqueID)`" />"

$Key = "<add key=`"uniqueID`" value=`"$uniqueID`" />"

强制 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.

您的代码未评估该值的原因是您使用单引号将变量 $key 括起来。用双引号包裹它并使用 sub-expression operator ($($UniqueID) 加上反引号就可以了,或者简单地使用 $UniqueID 也足够了。

关于powershell - 在 powershell 中连接字符串内的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51251007/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com