繁体   English   中英

如何从 c# 中的 powershell 脚本中捕获退出代码

[英]How to catch exit code from a powershell script in c#

我有一个由 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# 中的 PowerShell 脚本

// 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());
}

暂无
暂无

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

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