Cmdlet vs. PSCmslet - Windows PowerShell

When you write a Command-Let in Windows PowerShell, you must derive from one of the following classes: System.Management.Automation.Cmdlet or System.Management.Automation.PSCmdlet.

One of the most popular questions from beginners PowerShell developers, is "What's the difference?".
The answer is simple - PSCmdlet derives from Cmdlet and give more power and functionality. When you derive from PSCmdlet, you have a better interaction with the PowerShell runtime environment. it means that you can access the session state information, call script, access providers - and more access to the powershell runtime than when you derive from Cmdlet class.

Anyway, PSCmdlet, derives from Cmdlet too.

So, When derives from Cmdlet and when from PSCmdlet?
To answer, it's important to understand what's the disadvantage of deriving from PSCmdlet - you more depend in the PowerShell runtime.
When command-let (which every command-let is actually a class) derives from Cmdlet, it can be invoked directly, without using Runspace in some cases.
But, if you derive from PSCmdlet, you can't invoke the command lets directly (by simply create instance of them), and you must use Runspace to run commands that use your command-let.

In conclusion, deriving from Cmdlet is the best choice except when you need fully integration with powershell runtime, access to session state data, call scripts etc. Then, you have to derive from PSCmdlet.

Shahar.

3 Comments

Comments have been disabled for this content.