Friday, July 14, 2006

Access your classes in PowerShell

In this example, we will build a small class library and "shell out" to it in a PowerShell script. I know that it is dinky and lame, but bear with me. We will build on this knowledge in a later post. Here are the steps to reproduce the example.

Fire up your favorite text editor and paste in the following code. I'm using Notepad2 http://www.flos-freeware.ch/notepad2.html. It has c# syntax highlighting. Save your file as "Person.cs". For me, the full path look like "C:\Allen\Spikes\PSClassAccess\Person.cs".

using System;
using System.Text;

namespace Person
{
public class Phrases
{
public Phrases()
{
}

public static string Hello(string Name)
{
return "Hello " + Name;
}

public string GoodBye(string Name)
{
return "Goodbye " + Name;
}
}
}

Open up an instance of the Visual Studio command prompt. Then browse to your folder and enter the following command. If all goes well, you will now have a Person.dll file.

csc /target:library Person.cs
Open another instance of your text editor and paste in this code.

# This loads the dll into memory
[System.Reflection.Assembly]::loadfrom("C:\Allen\Spikes\PSClassAccess\Person.dll")

# Write a blank line for aesthetic reasons
echo("")

# Here we call the static method directly from the class.
[Person.Phrases]::Hello("Allen")

# Now lets create an instance of the class.
[Person.Phrases] $Greeter = New-Object -TypeName Person.Phrases

# Here we call the non-static method GoodBye.
$Greeter.GoodBye("Max")

Save your file as "HelloGoodbye.ps1". The "PS1" extension is PowerShells default extenstion for scripts. The first thing that we do in the script is load our dll into the shells memory. A couple of lines down we call the static Hello method. Notice that the type is enclosed in square brackets. Next we use the New-Object commandlet to create a new instance fo the Phrases class as $Greeter. In Powershell, all variables begin with the $ character. Finally we use the new object to call the Goodbye method.

So lets see what we get. Open up a PowerShell console and browse to the directory where you saved your script. Run the script by typing "./HelloGoodbye.ps1". Your results should look like the following:

PS> ./HelloGoodbye.ps1

GAC Version Location
--- ------- --------
False v2.0.50727 C:\Allen\Spikes\PSClassAccess\Person.dll

Hello Allen
Goodbye Max

Sweet! The first thing we see is the result from loading the dll. You'll quickly determine that it is not in the gac and was compiled with version 2 of the .NET framework. Then we see the results of our script. Its a beautiful thing.

This really shows the power and versatility of PowerShell. How many uses just popped into your head?

No comments: