powershell:如何评估字符串

问题描述 投票:0回答:3

我的文件

a.txt
包含:

delete from test_$suffix

我的 PowerShell 是:

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

如何操作

$a
来获取字符串
delete from test_tableA

powershell eval
3个回答
39
投票
$a=get-content a.txt
$suffix="tableA"

$ExecutionContext.InvokeCommand.ExpandString($a)

33
投票

Invoke-Expression
是等效的。

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

请参阅此博文了解更多信息。


3
投票

这是一种方法。双引号字符串中的变量会自动替换。只需确保您的输入文件符合此处字符串的 PS 规则即可。

 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
© www.soinside.com 2019 - 2024. All rights reserved.