Using .NET Framework Code from PowerShell

One of the coolest things about Windows PowerShell (Microsoft’s new command shell and scripting language) is that PowerShell code can call .NET code. You can think of the .NET Framework as a huge library of pre-written code. This allows you to easily perform tasks that aren’t possible with the old cmd.exe shell and .BAT files. Here’s an example PowerShell script that sends an HTTP request for a Web page, retrieves the response as HTML, and displays the result.
# file: gethtml.ps1
[System.Console]::WriteLine("Begin .NET demo`n")
$uri = "
$wc = new-object System.Net.WebClient
$b = $wc.DownloadData($uri)
$e = [System.Text.Encoding]::ASCII
$s = $e.GetString($b)
write-output $s
# end script
These commands could also be issued interactively in a PowerShell shell environment. The first statement calls the static WriteLine() method to print a message. Of course I don’t need .NET for this but it demonstrates how to call a static method. You can think of a static method as "good-to-go", meaning you simply call the method (using the correct syntax of course). Notice I use the PowerShell escape character (`) instead of the .NET escape character (\) to cause a newline after the start-up message. The next statement sets a string to my HTML target file. The third line of my script creates a new WebClient object, preparing to call an instance method. Most .NET methods are instance methods and you can think of them as methods which need to have a master object created before you can use these methods. On the fouth line I call the DownloadData() instance method. Notice it is attached to my $wc object, and that it returns an array of bytes which I store into a $b variable. Next I create an Encoding object using the static mechanism (this is a bit unusual because ::ASCII is actually a Property rather than a method). On the sixth line I use the GetString() instance method (attached to my Encoding object) to convert my result, which is currently in bytes, into a string. I finish by displaying my result string which yields:
Begin .NET demo
<p>Hello to you PowerShell</p>
So, the moral is that you can in fact call .NET code from PowerShell scripts. It’s too early to tell exactly how useful this ability is but I can see all kinds of possibilities for developers, testers, managers, and IT engineers.
This entry was posted in Software Test Automation. Bookmark the permalink.

One Response to Using .NET Framework Code from PowerShell

  1. Ahren says:

    We\’re using this in two instance already.In one case we load the Oracle .NET data provider and query  a database. The information is used in a number of scripts we\’ve written to automate some Oracle maintenance task.In another case our application developers had a c#  library written for some data encryption they were doing.So us lowly sys admins simply stole the library and are now using it to encrypt scripts we want to keep away from prying eyes.

Comments are closed.