捕获非常简单的Power Shell脚本的输出 [英] Capturing the output of a very simple power shell script

查看:95
本文介绍了捕获非常简单的Power Shell脚本的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想执行并捕获一个非常简单的powershell脚本的输出。
它是一个 Hello World脚本,看起来像这样。我使用了这篇帖子作为参考

I would like to execute and capture the output of a very simple powershell script. Its a "Hello World" script and it looks like this. I used this post for reference

filename:C:\scripts\test.ps1

Write-Host "Hello, World"

现在我想使用C#执行该脚本,所以我正在这样做

Now I would like to execute that script using C# so I am doing this

Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
PowerShell ps = PowerShell.Create();
ps.Runspace = runspace;
ps.Commands.AddScript(filename);
Collection<PSObject> results = ps.Invoke();

现在,当我运行这段代码时,结果什么也没有。关于如何解决此问题的任何建议?

Now when I run this code, I get nothing in results. Any suggestions on how I can resolve this issue?

推荐答案


我什么都没得到

I get nothing in results

未获得任何结果的主要原因是因为您正在使用写给主机 = https://docs.microsoft.com/zh-cn/powershell/module/microsoft.powershell.utility/write-host?view=powershell-6 rel = nofollow noreferrer>写入主机 ,这是错误

The primary reason you are not getting anything in results is because you are writing out to the host using Write-Host, this is wrong.

 Write-Host "Hello, World"

相反,您需要写输出

 Write-Output "Hello, World"

您也可以做(如果是最后一个)

You can also do (if it's the last item in the pipeline):

 "Hello, World"

在另一个音符上,哟您的代码可以简化为:

On another note, your code can be reduced to:

 PowerShell ps = PowerShell.Create();
 ps.Commands.AddScript("scriptPath");
 Collection<PSObject> results = ps.Invoke();

您不需要创建 Runspace 或者,如果您不是真正在处理并行任务...

You don't need to create a Runspace either if you are not really dealing with parallel tasks...

这篇关于捕获非常简单的Power Shell脚本的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆