【问题标题】:How to catch exit code from a powershell script in c#如何从 C# 中的 powershell 脚本中捕获退出代码
【发布时间】:2020-08-12 18:25:27
【问题描述】:

我有一个由 c# 运行的 powershell 脚本。以下是我的代码:

string data = System.IO.File.ReadAllText(@"C:\Users\user1\Desktop\power.ps1");
using (PowerShell PowerShellInstance = PowerShell.Create())
{
    PowerShellInstance.AddScript(data);
    IAsyncResult result = PowerShellInstance.BeginInvoke();
    while (!result.IsCompleted)
    {
        Logger.Info("Wait initiated");
        Thread.Sleep(5000);
    }
}

完成脚本后如何读取退出代码?

【问题讨论】:

    标签: c# asp.net .net windows powershell


    【解决方案1】:

    从这里Executing PowerShell scripts from C#

    // begin invoke execution on the pipeline
    // use this overload to specify an output stream buffer
    IAsyncResult result = PowerShellInstance.BeginInvoke<PSObject, PSObject>(null, outputCollection);
    
    ...
    
    foreach (PSObject outputItem in outputCollection)
    {
        //TODO: handle/process the output items if required
        Console.WriteLine(outputItem.BaseObject.ToString());
    }
    

    【讨论】:

    • 什么是 outputCollection?
    • PSDataCollection outputCollection = new PSDataCollection();
    猜你喜欢
    • 2021-08-16
    • 1970-01-01
    • 2011-07-15
    • 2013-08-28
    • 2010-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多