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 ?
Invoke-Expression is the equivalent.
$strExpression = "5 + 5 -eq 10"
Invoke-Expression $strExpression
True
See this blog post for more information.
$ExecutionContext.InvokeCommand.ExpandString() is not inherently safer, because arbitrary commands can be embedded in an expandable string via $(...); e.g., $ExecutionContext.InvokeCommand.ExpandString('$(Get-Date)')...ExpandString((gc myinput.txt).Replace('$','`$')) - there's probably some way to bypass this as well? Best to avoid expanding user input$suffix) is the very point of using $ExecutionContext.InvokeCommand.ExpandString() in the case at hand, the challenge is to selectively ignore embedded $(...) subexpressions. Doing this robustly, without getting tricked by escaping embedded in the source is somewhat tricky: $a = $a -replace '(?<!`)((?:``)*)\$\(', '$1`$$('$a=get-content a.txt
$suffix="tableA"
$ExecutionContext.InvokeCommand.ExpandString($a)
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