Sunday, July 6, 2008

How to Annoy Your Co-Workers (a.k.a. More Fun with .NET)

In this post by The PowerShell Guy (add it to your Google Reader if you haven't already), an annoying little prank is proposed for cheesing fools who leave their screens unlocked. It moves the mouse cursor to the top-left corner of the screen every 5 seconds or so.

I thought it sounded funny, so I typed it into PowerShell and got this:

PS C:\> do {[Windows.Forms.Cursor]::Position = "1,1";sleep 5}until (0)
Unable to find type [Windows.Forms.Cursor]: make sure that the assembly containing this type is loaded.
At line:1 char:27

So what did I do wrong? I thought at first that I'd misspelled it, but that wasn't the case. I typed it into PowerGUI ScriptEditor and ran the script, and it ran just fine.

I'd forgotten that not every .NET namespace is available in Powershell by default. Instead, you sometimes need to use this command:

PS C:\> [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")

If you did it right, you'll get an acknowledgement with the name of the .dll file that was loaded. If you misspell the namespace, you get no response at all, and no error (why?!?).

GAC Version Location
--- ------- --------
True v2.0.50727 C:\Windows\assembly\GAC_MSIL\System.Windows.Forms\2.0.0.0__b77a5c561934e089\System.Windows.Forms.dll

I figured that was a lot to type in at once, so I created another script, Load-Assembly.ps1:

[System.Reflection.Assembly]::LoadWithPartialName($ARGS[0])

Then I created an alias to that script called "load". Now when I want to import an assembly, I can just do this:

load System.Windows.Forms

It will make pwning my next victim so much easier. >:)

No comments: