Get Powershell errors from C #

Problem

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

Library

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;
    }
}

      

Calling the 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);
        }
    }
}

      

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.

thank

+3


source to share


2 answers


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

or in your code command.Streams.Error

.



+8


source


Try iterating through the collection results

:

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

      



This will give you the actual output from the console.

+1


source







All Articles