在 Powershell 中运行脚本时,我能够接收 Write-Host 输出,但在 C# 中则无法接收。
以下是输出 Write-Host“HELLO WORLD TEST”的代码。
当应用程序到达此行时失败:
Collection<PSObject> results = pipeline.Invoke()
;
我收到此错误消息:
HostException:由于宿主程序或命令类型不支持用户交互而提示用户失败的命令。尝试使用支持用户交互的主机程序(例如 Windows PowerShell 控制台或 Windows PowerShell ISE),并从不支持用户交互的命令类型(例如 Windows PowerShell 工作流)中删除与提示相关的命令
如何返回 Write-Host 的输出?提前致谢。
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
RunScript(@"C:\TestScript.ps1");
}
}
private string RunScript(string scriptText) {
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript(scriptText);
pipeline.Commands.Add("Out-String");
Collection < PSObject > results = pipeline.Invoke();
runspace.Close();
StringBuilder stringBuilder = new StringBuilder();
foreach(PSObject obj in results) {
//do something …
Run Code Online (Sandbox Code Playgroud)