Moving the Mouse Cursor with Windows PowerShell

We have several large displays with some rudimentary presentation software on them (displaying RSS feeds, video stream etc). Unfortunately this software is..not ideally written… For this reason I have published out a script to have the computers restart every morning at 5AM. Unfortunately, as a result of this reboot, we end up with the mouse cursor smack bang in the middle of the screen. In my discussions with one of our HelpDesk staff we concluded that a small script to move the mouse out of the way would be a far more ideal use of everyone’s time than for him to meander on over and move the mouse himself. Moving the mouse cursor with PowerShell is much easier than one may imagine.

First, load the .Net class System.Windows.Forms with the following command:

Add-Type -AssemblyName System.Windows.Forms

Secondly, let’s create an object that contains the dimensions of our screen. Because the “active corner” of the mouse cursor is the far top left pixel of the cursor, we can obscure all but this single pixel by placing it in the bottom right corner of the window, that is, x-max and y-max of the screen resolution. We’ll use the SystemInformation member VirtualScreen for this:

$screen = [System.Windows.Forms.SystemInformation]::VirtualScreen

By running a Get-Member over this new variable we can get a list of all the properties that are members of this VirtualScreen:

$screen | Get-Member -MemberType Property
TypeName: System.Drawing.Rectangle
Name     MemberType Definition
----     ---------- ----------
Bottom   Property   System.Int32 Bottom {get;}
Height   Property   System.Int32 Height {get;set;}
IsEmpty  Property   System.Boolean IsEmpty {get;}
Left     Property   System.Int32 Left {get;}
Location Property   System.Drawing.Point Location {get;set;}
Right    Property   System.Int32 Right {get;}
Size     Property   System.Drawing.Size Size {get;set;}
Top      Property   System.Int32 Top {get;}
Width    Property   System.Int32 Width {get;set;}
X        Property   System.Int32 X {get;set;}
Y        Property   System.Int32 Y {get;set;}

The properties here that are relevant are Width and Height (These are the two far-most points at the right-hand size and bottom of the display. Windows considers the origin of the screen (that is; coordinates (0,0)) to be the very top-left pixel of the screen. You can see here the results for my 1080p display:

PS> $screen.Width
PS> $screen.Height

After running this script, the mouse cursor will be at coordinates (1920,1080)

Finally, let’s change the cursor position to these variables:

[Windows.Forms.Cursor]::Position = "$($screen.Width),$($screen.Height)"

Simply hit go and watch your mouse cursor whiz away to the corner! Three lines of code takes about as much time to write and deploy as it would for the HelpDesk staff member in question to go and move the mouse on the displays. Scripting: 1. Humanity: 0.

Written on March 3, 2011