简体   繁体   English

Powershell 调用无效命令 output C#

[英]Powershell Invoke invalid command output C#

I have short C# code which fires an invalid command using powershell.我有简短的 C# 代码,它使用 powershell 触发无效命令。

using (PowerShell PowerShellInst = PowerShell.Create())
{
    PowerShellInst.AddScript("abc");
    Collection<PSObject> PSOutput = PowerShellInst.Invoke();
    Console.WriteLine(PSOutput);
}

Output is not printing anything. Output 没有打印任何东西。 when same command fire using actual powershell then following output is printed.当使用实际 powershell 触发相同的命令时,将打印以下 output。

在此处输入图像描述

How can I get error output in C sharp code?如何在 C 尖锐代码中得到错误 output?

To get the errors, you can check if the powershell object HadError then look into Streams.Error property of the powershell object and for each ErrorRecord , you can get the Exception, StackTrace, ToString, etc: To get the errors, you can check if the powershell object HadError then look into Streams.Error property of the powershell object and for each ErrorRecord , you can get the Exception, StackTrace, ToString, etc:

using (var powerShell = PowerShell.Create())
{
    var output = powerShell.AddScript("abc").Invoke();
    if(powerShell.HadErrors)
    {
        foreach(var error in powerShell.Streams.Error)
        {
            Console.WriteLine(error.ToString());
        }
    }
}

Note: PowerShell provides multiple streams for different purposes: Debug, Error, Information, Progress, Verbose, Warning.注意: PowerShell 为不同目的提供多个:调试、错误、信息、进度、详细、警告。 You can get the streams using Streams property of your powershell instance.您可以使用 powershell 实例的Streams属性获取流。

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

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