【问题标题】:Get Powershell errors from c#从 c# 获取 Powershell 错误
【发布时间】:2014-10-04 09:15:22
【问题描述】:

问题

我正在从 c# 调用 powershell 命令,但是,PowerShell 命令对象似乎只有属性 bool HasErrors,这并不能帮助我了解我收到的什么错误。

这就是我构建 powershell 命令的方式

图书馆

public static class PowerSheller
{
    public static Runspace MakeRunspace()
    {
        InitialSessionState session = InitialSessionState.CreateDefault();
        Runspace runspace = RunspaceFactory.CreateRunspace(session);
        runspace.Open();

        return runspace;
    }

    public static PowerShell MakePowershell(Runspace runspace)
    {
        PowerShell command = PowerShell.Create();
        command.Runspace = runspace;

        return command;
    }
}

调用 Move-Vm cmdlet

using (Runspace runspace = PowerSheller.MakeRunspace())
{
    using (PowerShell command = PowerSheller.MakePowershell(runspace))
    {
        command.AddCommand("Move-VM");
        command.AddParameter("Name", arguments.VMName);
        command.AddParameter("ComputerName", arguments.HostName);
        command.AddParameter("DestinationHost", arguments.DestinationHostName);

        if (arguments.MigrateStorage)
        {
            command.AddParameter("IncludeStorage");
            command.AddParameter("DestinationStoragePath", arguments.DestinationStoragePath);
        }

        try
        {
            IEnumerable<PSObject> results = command.Invoke();
            success = command.HasErrors;
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
    }
}

我期待在失败时会引发某种异常,但它却返回 0 个对象。而HasErrors 将导致知道命令是否成功;我仍然不确定如何获取特定错误,因为没有抛出异常。

谢谢

【问题讨论】:

  • 我强烈建议采用这种策略,而不是在 PowerShell 句柄上使用 ps.AddCommand(script).Invoke();;我有一个泄漏或其他东西,通过两次连续调用,后者永远不会被执行。使用运行空间,它可以正常工作。

标签: c# powershell error-handling


【解决方案1】:

要查看错误,请查看集合 PowerShell.Streams.Error 或您的代码 command.Streams.Error

【讨论】:

  • 我花了一段时间才回到这一点,必须先做一些其他事情。对于那些后来发现它的人。该命令抛出的异常在command.Streams.Error.ElementAt(0).Exception中的元素中可用(假设至少有1个元素)
【解决方案2】:

尝试遍历 results 集合:

foreach (PSObject psObject in results)
{
   ....do stuff with psObject (output to console, etc... you can use ToString() if you want)
}

这应该会让你得到控制台的实际输出。

【讨论】:

  • 我从调用中得到 0 个对象...我调用 PS 是否错误?
  • @ohmusama 可能。查看我提供的here 指导,了解如何从 C# 调用 PowerShell,看看它是否适合您。
猜你喜欢
  • 2018-11-18
  • 2021-11-01
  • 1970-01-01
  • 2010-12-15
  • 1970-01-01
  • 2012-01-21
  • 1970-01-01
  • 1970-01-01
  • 2013-02-17
相关资源
最近更新 更多