Friday, January 13, 2006

Creating a MSH Snap-in with MSH B3 - Part 2

In Creating a MSN Snap-in with MSH B3 Part 1, I showed you how easy it was to create a Snap-in. Well, at least I demonstrated the code for a snapin, one containing a simple cmdlet. In this blog article, I'll look at the details of how to compile and install your snap-in.

I have created a simple compilation script to compile snapins, csnap.msn, which take 3 paramaters (SnapinName, Snap-in Source file, and Snap-in DLL name. While you can provide paramaters, I use the convention that for a snapin , the source file is .cs, and the output is .dll. The script attempts a bit of intellegence here. The script next compiles your cmdlet, using the C# compiler, and copies the output dll to $MSHHOME, so consoles can later load the snap-in. Finally, we use the .NET Installer to install your cmd let and we're done. Well - we're done installing the snapin. Here is my cnap.msh script. A better formatted version is on, or will be soon!

# comples and installs an MSH snapin - V1.2.3
param ($snapin,$snapinsrc,$snapinout)
#some simple validation
if (!$snapin) {
Write-Host "Snap-in name not specified - try again."
# Examine 1st parm - if a single token,
# Or (1st param is two tokens and 2nd is .cs) then...
# make make intelligent choices in absence of src/output
if (($s.length -eq 2 -and $s[1].tostring() -match "cs") -or
($s.length -eq 1))
{if (!$snapinsrc){$snapinsrc = $snapin + ".cs"}
if (!$snapinout){$snapinout = $snapin + ".dll"}}
$x=$snapinout #save for later
#Output what we're doing
Write-host "Compiling: $snapinsrc"
Write-host "Output to: $snapinout"
# The C# compiler,and references we'll need
set-alias csc C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\csc.exe
$ref = "$env:programfiles\microsoft command shell\v1.0\System.Management.Automation.Dll"
# Compile it
&csc /target:library /out:$snapinout $snapinsrc /reference:$ref
#Copy it to its home
Write-Host "Copying : $x to $out"
$out= $mshhome + "\" + $snapinout
copy $x $out
# Finally Install it
$ins = "$env:windir\Microsoft.NET\Framework\v2.0.50727\installutil.exe"
&$ins $out
#all done
Write-Host "All Done"

So that's pretty much it! If you were to take the random number snap-in sample I posted last time, saved as random.cs, you'd call script by running:

./csnap random

In the next article in this series, I'll demo how to install and use your new snap-in.

No comments: