C# 捕获一个非常简单的powershell脚本的输出
我想执行并捕获一个非常简单的powershell脚本的输出。 这是一个“Hello World”脚本,看起来像这样。我用这篇文章作为参考C# 捕获一个非常简单的powershell脚本的输出,c#,powershell,C#,Powershell,我想执行并捕获一个非常简单的powershell脚本的输出。 这是一个“Hello World”脚本,看起来像这样。我用这篇文章作为参考 filename:C:\scripts\test.ps1 Write-Host "Hello, World" 现在我想使用C#执行该脚本,所以我正在这样做 Runspace runspace = RunspaceFactory.CreateRunspace(); runspace.Open(); PowerShell ps = PowerShell.Cre
filename:C:\scripts\test.ps1
Write-Host "Hello, World"
现在我想使用C#执行该脚本,所以我正在这样做
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
PowerShell ps = PowerShell.Create();
ps.Runspace = runspace;
ps.Commands.AddScript(filename);
Collection<PSObject> results = ps.Invoke();
Runspace Runspace=RunspaceFactory.CreateRunspace();
Open();
PowerShell ps=PowerShell.Create();
ps.运行空间=运行空间;
ps.Commands.AddScript(文件名);
收集结果=ps.Invoke();
现在,当我运行这段代码时,结果中什么都没有。对我如何解决这个问题有什么建议吗
我没有得到任何结果
您没有在结果中获得任何结果的主要原因是,您正在使用向主机写入内容,这是错误的
相反,你需要
您也可以这样做(如果它是管道中的最后一项):
另一方面,您的代码可以简化为:
PowerShell ps = PowerShell.Create();
ps.Commands.AddScript("scriptPath");
Collection<PSObject> results = ps.Invoke();
PowerShell ps=PowerShell.Create();
ps.Commands.AddScript(“脚本路径”);
收集结果=ps.Invoke();
如果你不是真的在处理并行任务,你也不需要创建一个
运行空间。一个甚至更多的点复制:。回答得好,但是请注意隐式输出特性(“Hello,World”
与显式写输出“Hello,World”
)与是否在最后一个管段中使用无关
Write-Output "Hello, World"
"Hello, World"
PowerShell ps = PowerShell.Create();
ps.Commands.AddScript("scriptPath");
Collection<PSObject> results = ps.Invoke();