Get Powershell errors from c#
To see the errors look at the collection PowerShell.Streams.Error
or in your code command.Streams.Error
.
ohmusama
I work for Microsoft coding all the c# I was also involved with the minecraft modding community. I have created a simple Biome Object Builder to hook into Phoenix Terrain Mod in c#. You can check it out http://faskerstudio.com/minecraft/BBOB
Updated on June 27, 2022Comments
-
ohmusama almost 2 years
Problem
I am invoking powershell commands from c# however, the
PowerShell
command object only seems to have the propertybool 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