且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何延迟PowerShell字符串中变量的扩展?

更新时间:2023-02-03 09:42:25

您可以使用Invoke-Expression来重新解析您的字符串-像这样:

You could use Invoke-Expression to have your string reparsed - something like this:

$string = 'The $animal says `"meow`"'
$animal = 'cat'
Invoke-Expression "Write-Host `"$string`""

请注意,必须如何在字符串中转义双引号(使用反引号),以免使解析器混乱.这包括原始字符串中的所有双引号.

Note how you have to escape the double quotes (using a backtick) inside your string to avoid confusing the parser. This includes any double quotes in the original string.

还请注意,第一个命令应该是一个命令,如果您需要使用结果字符串,只需使用write-output传递输出并将其分配给稍后可以使用的变量:

Also note that the first command should be a command, if you need to use the resulting string, just pipe the output using write-output and assign that to a variable you can use later:

$result = Invoke-Expression "write-output `"$string`""

如您的注释中所述,如果您无法修改字符串的创建以转义双引号,则您必须自己执行此操作.您也可以将其包装在一个函数中,以使其看起来更清晰:

As noted in your comments, if you can't modify the creation of the string to escape the double quotes, you will have to do this yourself. You can also wrap this in a function to make it look a little clearer:

function Invoke-String($str) { 
    $escapedString =  $str -replace '"', '`"'
    Invoke-Expression "Write-Output `"$escapedString`""
}

所以现在看起来像这样:

So now it would look like this:

# ~> $string = 'The $animal says "meow"'
# ~> $animal = 'cat'
# ~> Invoke-String $string
The cat says "meow"