在字符串定义中包含代码?

时间:2010-10-14 18:21:23

标签: string powershell

我有一个字符串

$string = "Active Directory"

我想制作另一个字符串

Active_Directory_Results.txt

我想做的事情

$otherstring = "$string.Replace(" ","_")_Results.txt"

但这没有用。什么是解决这个问题的正确方法?

2 个答案:

答案 0 :(得分:4)

你应该使用invoke-expression。原来的答案很好:

$otherstring = $string.Replace(" ","_") + "_Results.txt"

但实际上,你可以使用$(子表达式):

$otherstring = "$($string.Replace(" ","_"))_Results.txt"

$()告诉PowerShell在定义字符串之前评估它。

作为替代方案,您还可以使用字符串格式:

$otherstring = "{0}_Results.txt" -f $string.Replace(" ","_")

再次证明使用脚本语言,总有不止一种正确的方法......

答案 1 :(得分:2)

我现在不在我的Windows机器上,但$otherstring = $string.Replace(" ","_") + "_Results.txt"如何工作?

检查invoke-expression命令。它允许您在字符串中执行代码。 像:

PS> $command = '$otherstring = $string.Replace(" ","_") + "_Results.txt"'
PS> Invoke-Expression $command