Sunday, May 4, 2014

How to call custom cmdlet’s from PowerShell Script/How to create a custom cmdlet project in PowerShell

·         Open visual Studio

·         Create a Class library project

·         Add a new class file
The file will have be inheriting “System.Management.Automation.Cmdlet” .The file will also decorate the class file with the following verb [Cmdlet(VerbsCommon.Add, "NameOfYourFunctionality")]
Some sample code showing a sample powershell file


    [Cmdlet(VerbsCommon.Add, " NameOfYourFunctionality ")]
    public class MyClass : System.Management.Automation.Cmdlet
    {
        [Parameter(Position = 0, Mandatory = true)]
  public string para1;
   // define more parameters here
protected override void ProcessRecord()
        {

              //write your functionality here
 }

Add more class files if you need to build your functionality

·         Add a new installer file
Add the following code to the installer class
    [RunInstaller(true)]
    public class Installer : PSSnapIn
{
       public override string Name
        {
            get
            {
                return "NameWithWhichYouWantToRegisterWhenYouImportusing Add-PSSnapin";
            }
        }
}
}

·         Strong sign your assembly
·         In order to call this custom cmdlet from a script file you may have to first register this assembly in the GAC using the GACUTIL , once that is done you can use this custom cmdlet using the following commands in the script file

Add-PSSnapin NameWhichYoudefinedInTheNamePropertyOfinstallerFile -ErrorAction "Stop"

No comments:

Post a Comment