Powershell中字符串内的Concat变量

时间:2018-07-09 17:26:54

标签: powershell

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

代码

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

我想要的结果

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

我得到的结果

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

2 个答案:

答案 0 :(得分:4)

尝试一下-

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

OR

$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也足够。

答案 1 :(得分:0)

我发现使用'-f'格式设置选项非常适合这种请求。试试:

$uniqueID = "123"
$Key = ('<add key="{0}" value="{1}" />' -f 'uniqueID', $uniqueID)
write-host $Key