从c#获取Powershell错误

ohm*_*ama 6 c# error-handling powershell

问题

我从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;
    }
}
Run Code Online (Sandbox Code Playgroud)

调用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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

谢谢

Kei*_*ill 17

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

  • 我花了一段时间才回到这个,不得不先做一些其他的事情。对于那些后来发现这一点的人。命令抛出的异常在`command.Streams.Error.ElementAt(0).Exception`中的元素中可用(假设至少有1个元素) (3认同)