Problem
I am invoking powershell commands from c# however, the PowerShell
command object only seems to have the property bool HasErrors
which doesn't help me know what error I received.
This is how I build my 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;
}
}
Invoking 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 sort of exception to be thrown on failure, but instead it returns 0 objects. While HasErrors
will result in knowing if the command was successful or not; I'm still not sure how to get the specific error, as no exception is thrown.
Thanks