简体   繁体   English

如何从 C# 中的 Powershell 脚本读取写入主机 output

[英]How to read Write-Host output from Powershell script in C#

When running the script in Powershell i'm able to receive the Write-Host output but not in C#.在 Powershell 中运行脚本时,我能够接收写入主机 output 但不能在 C# 中接收。
Here is the code for the output Write-Host "HELLO WORLD TEST."这是 output 写入主机“HELLO WORLD TEST”的代码。
The application fails when it reaches this line:应用程序在到达此行时失败:
Collection<PSObject> results = pipeline.Invoke() ; Collection<PSObject> results = pipeline.Invoke() ;
I receive this error message:我收到此错误消息:

HostException: A command that prompts the user failed because the host program or the command type does not support user interaction. HostException:提示用户的命令失败,因为主机程序或命令类型不支持用户交互。 Try a host program that supports user interaction, such as the Windows PowerShell Console or Windows PowerShell ISE, and remove prompt-related commands from command types that do not support user interaction, such as Windows PowerShell workflows Try a host program that supports user interaction, such as the Windows PowerShell Console or Windows PowerShell ISE, and remove prompt-related commands from command types that do not support user interaction, such as Windows PowerShell workflows

How can I return the output of Write-Host?如何返回 Write-Host 的 output? Thanks in advance.提前致谢。

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
    }
    return Textbox.Text;
}

You can work with PowerShell like this.您可以像这样使用 PowerShell。 Create an instance and add listeners for all the Powershell streams that are of interest to you:创建一个实例并为您感兴趣的所有 Powershell 流添加侦听器:

private string RunScript(string scriptText)
{


    System.Management.Automation.PowerShell powerShellInstance = System.Management.Automation.PowerShell.Create();

powerShellInstance.Streams.Information.DataAdded += InformationHandler;

    powerShellInstance.Streams.Verbose.DataAdded += InformationalRecordEventHandler<VerboseRecord>;

    powerShellInstance.Streams.Debug.DataAdded += InformationalRecordEventHandler<DebugRecord>;

    powerShellInstance.Streams.Warning.DataAdded += InformationalRecordEventHandler<WarningRecord>;

    powerShellInstance.AddScript(scriptText);
                        powerShellInstance.Invoke();               
}

 static void InformationalRecordEventHandler<T>(object sender, DataAddedEventArgs e) 
        where T : InformationalRecord
    {
        var newRecord = ((PSDataCollection<T>)sender)[e.Index];
        if (!string.IsNullOrEmpty(newRecord.Message))
        {
            //STORE your message somewhere
        }
    }

static void InformationHandler(object sender, DataAddedEventArgs e)
    {
        var newRecord = ((PSDataCollection<InformationRecord>)sender)[e.Index];
        if (newRecord?.MessageData != null)
        {
            //STORE your message somewhere
        }
    }

If you want to keep using the Pipeline class, you can use the Command.MergeMyResults method .如果您想继续使用管道 class,可以使用Command.MergeMyResults 方法 For example, to redirect all type of streams to pipeline output:例如,要将所有类型的流重定向到管道 output:

private string RunScript(string scriptText) {

    Runspace runspace = RunspaceFactory.CreateRunspace();

    runspace.Open();

    Pipeline pipeline = runspace.CreatePipeline();
    pipeline.Commands.AddScript("Write-Host Test");
    pipeline.Commands[pipeline.Commands.Count-1]
       .MergeMyResults(PipelineResultTypes.All, PipelineResultTypes.Output)
    
    Collection < PSObject > results = pipeline.Invoke();

    runspace.Close();

    foreach(PSObject obj in results) {
        Console.WriteLine(obj.ToString());
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM