powershell: how to evaluate a string read from a file

时光怂恿深爱的人放手 提交于 2019-11-29 11:12:22

问题


file a.txt is:

delete from test_$suffix

$a=get-content a.txt

$suffix="tableA"

how to manipulate the variable to set it as

delete from test_tableA


回答1:


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

$ExecutionContext.InvokeCommand.ExpandString($a)



回答2:


Invoke-Expression is the equivalent.

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

See http://technet.microsoft.com/en-us/library/ee176880.aspx for more information.




回答3:


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


来源:https://stackoverflow.com/questions/4836703/powershell-how-to-evaluate-a-string-read-from-a-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!