a space for me to share weird problems and hacks i encounter in my profession

fredag den 4. marts 2011

Implementing PowerShell in applications - Part 1

I created a few applications doing the last 2 years that facilitate PowerShell. I really had a hard time getting around to look at PowerShell, I honestly though VB scripts where so more powerful and easier to write, but looking back now I really don’t see why. I love it. I love it so much, that I create several applications that have a built-in PowerShell engine.And how does that work then, you might ask ? well, there's tons of examples out there, but do a Google search on “Runspaces” or “Management.Automation.Runspaces” and your well on your way. There is how ever a few things, you want to keep in mind.A plain PowerShell will often not be enough so you need some modules or snap ins. Let get down to basics here. Create a new application, go to My Project –> References –> Add –> Browse –> C:\Windows\assembly\GAC_MSIL\System.Management.Automation and find System.Management.Automation.dll

See, that wasn’t so bad was it ? Here's with some Snap ins loaded from start. ( you can also just call invoke “Add-PSSnapin Name” .. use Get-PSSnapin –Registered to see what is available to you.

Here's another “gotcha” … Many snap ins only works on x86 and some only on x64. If you see something in your PowerShell and get The Windows PowerShell snap-in 'SqlServerCmdletSnapin100' is not installed on this machine.

It means you compiling for the wrong version. Go to My Project –> Advanced Compiler Options…” and choose the correct version. NEVER choose anyCPU.

It’s blank … the reason is PowerShell commands return objects, not text. Write-Host is sending the text to the Host holding the runespace. the handy little wrapper class PowerShell implements a simple Host and HostUI, but this doesn’t support neat things like Read, Write, Prompt etc..

So, lets make one, that does. ( Remember to add a reference to “System.Drawing” )Add the following 3 classes