Ed Wilson: On form and function

One of the fun things about being the Microsoft Scripting Guy is reading all the e-mail sent to Scripter@Microsoft.Com. Each week, I attempt to answer the several hundred e-mails that I get, at times with varying success. One common form of e-mail I get goes something like this: I need a WMI script to swap the mouse buttons on 100 computers at work … or words to that effect. The easy answer to that particular question is, it cannot be done. You can detect if you have a right handed mouse, or a left handed mouse, but the handedness property is read-only on the Win32_PointingDevice WMI class.

The long answer to the question of the mouse, is that while you cannot use WMI to solve the problem, you can write a script that uses P-Invoke and some of the new features of Windows PowerShell 2.0. The SwapMouseFunction.ps1 script illustrates this technique.

# ------------------------------------------------------------------------
# NAME: SwapMouseFunction.ps1
# AUTHOR: ed wilson, Microsoft
# DATE: 2/13/2009
#
# KEYWORDS: Add-Type, user32.dll, mouse, pinvoke
#
# COMMENTS: This script uses Add-Type to create a
# function from user32.dll that allows you to swap the
# mouse button.
#
#
# ------------------------------------------------------------------------
#Requires -Version 2.0
Function Add-User32Mouse
{
$signature = @"
[DllImport("user32.dll")]
public static extern bool SwapMouseButton(bool fSwap);
"@

Add-Type -memberDefinition $signature -name "Win32SwapMouseButton" -namespace Win32Functions -passThru
} #End Add-User32Mouse

# *** EntryPoint to script ***
#$SwapMouse = Add-User32Mouse
#[void]$SwapMouse::SwapMouseButton($False)
[void](Add-User32Mouse)::SwapMouseButton($False)

You see, the thing is, the person who sent the e-mail asking for a WMI script to change the mouse buttons assumed that because they used WMI to detect the primary and secondary mouse buttons, that they should also use WMI to change the mouse buttons. Such an assumption when working with scripting leads to tunnel vision, and convoluted scripts at best, and to misleading and inconsistent results at worst. Rather than assume what technology you will use to solve the problem in a script, it is best to clearly define the problem, and then choose the best approach from the available technology to solve your problem.

Contrary to building buildings, in programming the form dictates which function you will use and not vice versa. Now we have both the long answer, and the short answer to the problem of the mouse.

Technorati Tags: Ed Wilson,WMI,Windows PowerShell