Question:
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
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 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
Answer:
To see the errors look at the collection PowerShell.Streams.Error
or in your code command.Streams.Error
.