C# PowerShell - AddScript 作为多个语句
C# PowerShell - AddScript as multiple statements
我正在努力寻找一种在 C# 中执行多行和多语句 PowerShell 脚本的方法,以便所有结果都可以从 Invoke() 方法获得。
PowerShell.AddScript 添加的命令似乎总是一起流水线化。但我希望它们被读取、解析和 作为多个语句执行,并将各个语句的所有结果写入输出 .
这可能吗?
我现在做什么:
using PowerShell powerShell = PowerShell.Create();
powerShell.AddCommand("Set-ExecutionPolicy").AddArgument("Unrestricted").AddParameter("Scope", "CurrentUser").AddStatement();
powerShell.AddScript(@"multiple powershell statements
on multiple rows, some of them writing to output"); //No intermediate results will be logged or printed as the script is added as a single pipeline
powerShell.AddScript("$?"); //This is to echo the execution status of the last command into results
var results = powerShell.Invoke();
results集合只有一个结果,就是最后一个$?然后我查询以找出 pass/fail 信息的语句。我也查询错误流,但这与问题无关。
问题是:我收到 PowerShell 脚本作为用户输入,因此无法修改它和添加 as 语句。我正在考虑逐行添加脚本,但它会破坏可能的多行管道、代码块等。因此,为了达到我想要的结果,我需要自己解析脚本,这听起来很复杂。 是否有任何优雅的解决方案来接收来自 Invoke() 的所有结果,最重要的是,从用户输入添加一个复杂的脚本,而不会将其作为单个管道压缩在一起,将一个命令的结果提供给另一个?
简单地使用字符串连接将$?
语句附加到收到的语句,前面是;
(语句分隔符):
powerShell.AddScript(@"multiple powershell statements
on multiple rows, some of them writing to output" + ";$?");
这样,所有语句都作为单个脚本 [块](一段 PowerShell 代码)提交。
连续 .AddScript()
次通话不累积 - 最后一次 "wins".
或者,将 .AddStatement()
附加到每个 .AddScript()
调用 ,类似于您已经为改变的 .AddCommand()
调用所做的执行政策。
但是,使用单个 .AddScript()
调用 ,仅传递 单个 一段 PowerShell 代码效率更高,如上图
最后,强制性的安全警告:
I receive the PowerShell script as a user input
除非您首先检查并可能清理输入,否则只有在您信任来源时才执行它。
我正在努力寻找一种在 C# 中执行多行和多语句 PowerShell 脚本的方法,以便所有结果都可以从 Invoke() 方法获得。 PowerShell.AddScript 添加的命令似乎总是一起流水线化。但我希望它们被读取、解析和 作为多个语句执行,并将各个语句的所有结果写入输出 .
这可能吗?
我现在做什么:
using PowerShell powerShell = PowerShell.Create();
powerShell.AddCommand("Set-ExecutionPolicy").AddArgument("Unrestricted").AddParameter("Scope", "CurrentUser").AddStatement();
powerShell.AddScript(@"multiple powershell statements
on multiple rows, some of them writing to output"); //No intermediate results will be logged or printed as the script is added as a single pipeline
powerShell.AddScript("$?"); //This is to echo the execution status of the last command into results
var results = powerShell.Invoke();
results集合只有一个结果,就是最后一个$?然后我查询以找出 pass/fail 信息的语句。我也查询错误流,但这与问题无关。
问题是:我收到 PowerShell 脚本作为用户输入,因此无法修改它和添加 as 语句。我正在考虑逐行添加脚本,但它会破坏可能的多行管道、代码块等。因此,为了达到我想要的结果,我需要自己解析脚本,这听起来很复杂。 是否有任何优雅的解决方案来接收来自 Invoke() 的所有结果,最重要的是,从用户输入添加一个复杂的脚本,而不会将其作为单个管道压缩在一起,将一个命令的结果提供给另一个?
简单地使用字符串连接将$?
语句附加到收到的语句,前面是;
(语句分隔符):
powerShell.AddScript(@"multiple powershell statements
on multiple rows, some of them writing to output" + ";$?");
这样,所有语句都作为单个脚本 [块](一段 PowerShell 代码)提交。
连续 .AddScript()
次通话不累积 - 最后一次 "wins".
或者,将 .AddStatement()
附加到每个 .AddScript()
调用 ,类似于您已经为改变的 .AddCommand()
调用所做的执行政策。
但是,使用单个 .AddScript()
调用 ,仅传递 单个 一段 PowerShell 代码效率更高,如上图
最后,强制性的安全警告:
I receive the PowerShell script as a user input
除非您首先检查并可能清理输入,否则只有在您信任来源时才执行它。