Comparison Cmdlet to PSCmdlet
The
Cmdlet
class provides some common functionality for
cmdLets, such as
object output and
record processing.
Thus, deriving a class from
Cmdlet
is the common way to create a user defined
cmdLet.
A derived class is
System.Management.Automation.PSCmdlet
. If a cmdLet-class is derived from
PSCmdlet
, the cmdLet also has access to the
MSH runtime, including variables in the session state, access to the host or information about the current cmdlet providers.
BeginProcessing(), ProcessRecord() and EndProcessing() methods
When deriving a class from
Cmdlet
to create a new command, the three methods
BeginProcessing()
,
ProcessRecord()
and
EndProcessing()
can be overridden to initialize command execution, process each object that the command receives from the
pipeline, and clean up command execution.
Simple C-Sharp example
The following simple source code demonstrates how a
cmdLet can be written in
C#:
//
// csc -r:"C:\Program Files (x86)\Reference Assemblies\Microsoft\WindowsPowerShell\3.0\system.management.automation.dll" -target:library Add-Strings.cs
//
// import-module .\Add-Strings.dll
//
// Add-Strings foo bar
//
using System.Management.Automation;
[Cmdlet("Add", "Strings")]
[OutputType("System.String")]
public class AddStrings : Cmdlet {
//
// Specify the two parameters for the cmdlet:
//
[Parameter(Position=0, Mandatory=true)]
public string Text1 {
get { return t1; }
set { t1 = value; }
}
[Parameter(Position=1, Mandatory=true)]
public string Text2 {
get { return t2; }
set { t2 = value; }
}
private string t1;
private string t2;
//
// Define functionality of cmdlet by
// overriding ProcessRecord.
// This method will be called when the
// cmdlet is executed.
//
protected override void ProcessRecord() {
//
// WriteObject(…) puts an object into
// the output pipe:
//
WriteObject(Text1 + " " + Text2);
}
}
The source code can be compiled with into a
DLL (
Add-Strings.dll
) with:
csc.exe -r:"C:\Program Files (x86)\Reference Assemblies\Microsoft\WindowsPowerShell\3.0\system.management.automation.dll" -target:library Add-Strings.cs
This DLL must then be imported into a
session with
import-module .\Add-Strings.cs
With this import, the cmdlet is available to be used:
Add-Strings foo bar