Daniel Wu
Daniel Wu

Reputation: 6003

powershell: how to evaluate a string

My file a.txt contains:

delete from test_$suffix

My PowerShell is:

$a = get-content a.txt
$suffix = "tableA"

How would I manipulate $a to obtain the string delete from test_tableA ?

Upvotes: 26

Views: 41969

Answers (3)

Stephan Unrau
Stephan Unrau

Reputation: 450

Invoke-Expression is the equivalent.

$strExpression = "5 + 5 -eq 10"
Invoke-Expression $strExpression
True

See this blog post for more information.

Upvotes: 40

Doug Finke
Doug Finke

Reputation: 6823

$a=get-content a.txt
$suffix="tableA"

$ExecutionContext.InvokeCommand.ExpandString($a)

Upvotes: 40

mjolinor
mjolinor

Reputation: 68331

Here's one way. Variables in a double-quoted here-string get substituted automatically. Just be sure your input file conforms to the PS rules for here-strings.

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

 $suffix = "tableA"

 get-content testfile.txt

 delete from test_$suffix

 get-content testfile.txt | convertto-herestring

 delete from test_tableA

Upvotes: 3

Related Questions