Building a PowerShell cmdlet using C# - Part 3: Using the Output Streams

Now that we've seen how to setup the code base for a cmdlet and how to debug it, let's take a look on how it will interact with the world via the various output streams.

Verbose Output - WriteVerbose()

One of the most useful functions of every cmdlet. Provides detailed information about the execution of the command.

Debug Output - WriteDebug()

The latest versions of PowerShell give the ability to debug to the end users. The -Debug parameter along with the WriteDebug method, pause the execution at specific points so that the end user can debug it.

Warning Output - WriteWarning()

It goes without saying that if any issues arise during the execution of the cmdlet, those should be reported to the user. For minor issues that do not have an impact on the result of the command, use the WriteWarning method.

Errors - WriteError()

However, when there are issues that do have an impact on the result, we have to inform the user about them. Things get a little bit complex here, since we have to create error record objects. These errors are NonTerminating, meaning that the execution will not stop after the WriteError command.

Exceptions - Throw()

If the severity of the error is such that the execution should be stopped at all times, it's time for the Throw command. This command will throw an exception and the execution will stop.

The -ErrorAction parameter allows the end users to treat not terminating errors as exceptions in order to handle them using try/catch blocks. Read more on how to handle errors here.

Console Output - WriteLine()

To write a string message to the host window, use the WriteLine method.

Standard Output - WriteObject()

Last but surely not least, the WriteObject method will send an object down the pipeline. This is how your cmdlet will return any objects.

On the next article we'll see how to package the cmdlet into a module.

Till then, have fun!

Popular posts from this blog

Domain Controller Machine Password Reset

Configuring a Certificate on Exchange Receive Connector

Verbose Parameter Passing to cmdlet inside Function