Test if PSObject originated from WriteObject() WriteWarning() WriteError()

167 views Asked by At

Stack,

How do you distinguish with PSObjects are created by WriteObject() WriteWarning() WriteError()?

Starting with this:

psCmd = PowerShell.Create();
Runspace = RunspaceFactory.CreateRunspace();
Runspace.Open();
psCmd.Runspace = Runspace;
psCmd.AddCommand(cmdletName);
Collection<PSObject> results = null;
results = psCmd.Invoke();

The results variable contains the all the PSObjects piped out the commandlet. How do you identify PSObjects that were created by WriteObject() WriteError() WriteWarning() by the commandlet?

I want add code that achieves the following:

foreach(psObj in results) {
   if ( IsWarning(psObj) ) 
   {
     // Turn on yellow flashing lights
   } 
   else if ( IsError(psObj) )
   {
     // Turn on red flashing lights
   }
   else
   {
     // Write to ticker-tape
   }
}
1

There are 1 answers

0
manojlds On

You should be able to use the Streams property on the Powershell object (psCmd) to the errors and other messages and handle them appropriately:

if (psCmd.Streams.Error.Count > 0)
{
  Console.WriteLine("{0} errors", psCmd.Streams.Error.Count);
}

Similarly, you can access warning, debug, progress and verbose.

Learn more about it here: http://msdn.microsoft.com/en-us/library/system.management.automation.psdatastreams_members(v=vs.85).ASPX