开发者

Dynamic string parsing in Powershell

I'm trying to do something unusual with Powershell parsing. Basically, I have a literal string that contains the name of a variable. What I would like to do is tell powershell "Hey, I've got a string that (may) contain one or more variable names--dynamically parse it, replacing the variable names with their values"

Here's the textbook way I un开发者_运维百科derstand parsing works:

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

And if I now change the value for $foo:

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

No surprises here. The value of $bar was parsed as it was assigned, and didn't change simply because the value of $foo changed.

Ok, so What if we assign $bar with a single quote?

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

That's great, but is there a way to get Powershell to parse it on demand? For example:

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

Why do I want to do this? I would like to be able to get content from a file (or some data source) and dynamically parse it:

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.

Can this be done? I realize I could do some pattern matching for search/replace for known names, but I'd rather have Powershell reparse the string.

Thanks!


$executionContext.InvokeCommand.ExpandString($bar)

http://powershell.com/cs/blogs/ebook/archive/2009/03/30/chapter-12-command-discovery-and-scriptblocks.aspx


I wrote a convertto-herestring function that does just that:

 $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.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜