Get Powershell errors from C #


I am calling powershell commands from C #, however, the command object PowerShell

only has a property bool HasErrors

which does not help me know what error I got.

This is how I am building the powershell command


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

        return runspace;

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

        return command;


Calling the Move-Vm cmdlet

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

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

            IEnumerable<PSObject> results = command.Invoke();
            success = command.HasErrors;
        catch (Exception e)


I was expecting some kind of exception to crash, but instead it returns 0 objects. So far HasErrors

will lead to knowing whether the team was successful or not; I still don't know how to get the specific error as no exception is thrown.



source to share

2 answers

To see errors, look at the collection PowerShell.Streams.Error

or in your code command.Streams.Error




Try iterating through the collection results


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


This will give you the actual output from the console.



All Articles