1

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 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.