After a long time ,I am little bit free from the office works…So obviously started learning new things.One of the pending item was Windows PowerShell which I started some time back.There is no need to explain what is Windows Power Shell.If you don’t know just google it :-)
Being developers,just running a command or writing a script file is not our aim.We need to extend the functionality for the power shell for the end users.How to extend the functionality? It is by writing commandlets.
What is cmdlet (commandlet) ?
The exact definition of CmdLet ,can be obtained from msdn.If we think from a developer perspective CmdLet is
A sub class of PSCmdlet class compiled into a .net dll, with some overridable methods encapsulating the command implementation which can be invoked through power shell command or power shell apis.
Steps to create a CmdLet
- Create a class library
- Add References
- System.Management.Automation.dll located at C:\Program Files\Reference Assemblies\Microsoft\WindowsPowerShell\v1.0\
- Write classes for Installer by sub classing PSSnapIn and Cmdlet by subclassing PSCmdlet
- Compile the code and install the cmdlet using InstallUtil.exe present here C:\Windows\Microsoft.NET\Framework\v4.0.30319\
- In the Power shell window, register your cmdlet by using the command Add-PSSnapIn <snapinname>
- Run the cmdlet from power shell command window.
Telling these steps is very simple…I found the same in so many sites.But when I tried to create my first sample I faced so many issues…So try to create the cmdlet by yourself using these steps else read the rest of this article.If you create a cmdlet by just reading till here ,I will say you have got excellent googling skills.
Writing C# to create cmdlet
There is no question in creating a class library and adding references if the path is known.Below is the code for installer class.
All the functionalities are wrapped into the base class.So here we just need to give the name and other details only.If you reflect the codes of its base classes you can see the code which does all the installation.
Now coming to the real cmdlet class.
There are 3 methods which are overriding base class methods.Among those, the ProcessRecord is the one which we need.We can write the code to output the ip from here.The WriteIPAddress method writes the ipaddress using WriteObject method.
Now coding done.Compile the dll and get the copy of that dll to your desired location say c:\cmdlets.Now here is the cmd to install the snap in.
Now we need to register using the command
All set run the command get-ip to get the ipaddress
1.For running installutil,you may need to give the full path to that exe file
2.add-pssnapin expects the parameter which is same what you have given in the Name property of the installer class IPSnapIn.If you have any confusion on the name use the command get-pssnapin –registered to find out the snapin names.