将Powershell窗口的输出提取为字符串

时间:2018-06-02 13:48:51

标签: c# powershell

在我的C#应用​​程序中,我必须运行一些PowerShell脚本。我从this site代码复制了关于如何运行脚本的粘贴。

我的问题:假设我想使用链接中的代码,如何将PowerShell输出提取到某个字符串或某个.txt文件?

编辑:

如果您想测试此代码以回复此帖子,您需要:

  • 添加对System.Management.Automation dll
  • 的引用
  • requireAdministrator
  • 中添加app.manifest

1 个答案:

答案 0 :(得分:1)

基于this link,您可以使用Collection<PSObject> results = pipeline.Invoke();提取输出,这里是一个代码示例,请注意这会将PowerShell输出解压缩到StringBuiler并隐藏PowerShell窗口:

 string RunScript(string pathToYourScript){
RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();

            using (var runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration))
            {
                runspace.Open();
                runspace.SessionStateProxy.SetVariable("prog", this);

                using (Pipeline pipeline = runspace.CreatePipeline())
                {
                    if (!string.IsNullOrEmpty(path))
                        pipeline.Commands.AddScript(string.Format("$env:path = \"{0};\" + $env:path", pathToYourScript));

                    pipeline.Commands.AddScript(path);
                    pipeline.Commands.Add("Out-String");

                    Collection<PSObject> results = pipeline.Invoke();
                    StringBuilder stringBuilder = new StringBuilder();
                    foreach (PSObject obj in results)
                    {
                        stringBuilder.AppendLine(obj.ToString());

                    }

                    var outDefault = new Command("out-default");
                    outDefault.MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);
                    pipeline.Commands.Add(outDefault);

                    return stringBuilder;
                    }

                }
            }