2011-02-17 49 views
2

我试图做一些与Powershell解析不同寻常的事情。基本上,我有一个包含变量名称的文字字符串。我想要做的是告诉powershell“嗨,我有一个字符串(可能)包含一个或多个变量名称 - 动态解析它,用它们的值替换变量名称”PowerShell中的动态字符串解析

这里是教科书的方式我明白解析作品:

PS C:\> $foo = "Rock on" 
PS C:\> $bar = "$foo" 
PS C:\> $bar 
Rock on 

如果我现在改变了价值$ foo的:

PS C:\> $foo = "Rock off" 
PS C:\> $bar 
Rock on 

没有意外在这里。 $ bar的值在分配时被解析,并且因为$ foo的值改变而没有改变。

好吧,那么如果我们为$ bar分配单引号会怎么样?

PS C:\> $foo = "Rock on" 
PS C:\> $bar = '$foo' 
PS C:\> $bar 
$foo 

这很好,但有没有办法让Powershell按需解析它?例如:

PS C:\> $foo = "Rock on" 
PS C:\> $bar = '$foo' 
PS C:\> $bar 
$foo 
PS C:\> Some-ParseFunction $bar 
Rock on 
PS C:\> $foo = "Rock off" 
PS C:\> Some-ParseFunction $bar 
Rock off 

为什么我要这样做?我希望能够从一个文件(或数据源)获取内容并动态解析它:

PS C:\> $foo = "Rock on" 
PS C:\> '$foo with your bad self.' | out-file message.txt 
PS C:\> $bar = (get-content message.txt) 
PS C:\> $bar 
$foo with your bad self. 
PS C:\> Some-ParseFunction $bar 
Rock on with your bad self. 

可以这样做?我意识到我可以为搜索/替换已知名称做一些模式匹配,但我宁愿让Powershell重新分析字符串。

谢谢!

回答

0

我写了的ConvertTo-herestring功能做到了这一点:

$foo = "Rock on" 
'$foo with your bad self.' | out-file message.txt 

function convertto-herestring { 
begin {$temp_h_string = '@"' + "`n"} 
process {$temp_h_string += $_ + "`n"} 
end { 
    $temp_h_string += '"@' 
    iex $temp_h_string 
    } 
} 

    gc message.txt | convertto-herestring 

    Rock on with your bad self.