Script Tips

Exposed Through Scripting

Essential #2: A script for launching executables, sending keystrokes, anything that needs to be automated.

I’m often told, “such-and-such is easy to modify from the Windows user interface, but I can’t find a way to script it.” Sadly, that’s often the case—not everything in Windows is exposed in a way that scripting can make use of. This time around, as a continuation of my "essentials" theme for this column, I want to show you how to automate stuff that isn’t directly exposed through scripting.

See, scripting can launch executables, make their window active, and send keystrokes, including arrow keys, tabs, and other keys that let you navigate a UI without using a mouse. Take this gem:

'first we'll launch Notepad - this could be ANY app
'we'll specify that the script NOT wait for it
'to finish running
Dim objShell
Set objShell = CreateObject("WScript.Shell")
objShell.Run "C:\Windows\System32\Notepad.exe",,False

'we will wait a second for the app to start
WScript.Sleep 1000

'now we need to activate the windows. we need it's window
'title, which by experimentation we've determined Is
'"Untitled - Notepad." You don't need the EXACT title;
'Windows will try to activate the first matching window
'it finds
objShell.AppActivate "Untitled - Notepad"

'now we can send keystroked - see the WshShell docs
'for details on what this can Do

'we'll start with simple text
objShell.SendKeys "Hello, scripter "

'to send a square bracket you have to enclose it in curly braces
objShell.SendKeys "{[}If indeed you are a scripter{]}"

'special keys have a name you can send
objShell.SendKeys "{HOME}To whom it may concern:{ENTER}{ENTER}"

You can find a longer version of the script on the Essentials page at ScriptingAnswers.com; the script includes a brief reference to other key codes. Of course, the docs for the WshShell object provide a complete reference. This is a great way to automate tasks that aren’t otherwise easily scriptable. Because Microsoft has taken great care to make the Windows UI accessible to folks who can’t operate a mouse, almost everything is controllable from the keyboard if you need to, meaning it’s controllable via SendKeys, as well.

About the Author

Don Jones is a multiple-year recipient of Microsoft’s MVP Award, and is Curriculum Director for IT Pro Content for video training company Pluralsight. Don is also a co-founder and President of PowerShell.org, a community dedicated to Microsoft’s Windows PowerShell technology. Don has more than two decades of experience in the IT industry, and specializes in the Microsoft business technology platform. He’s the author of more than 50 technology books, an accomplished IT journalist, and a sought-after speaker and instructor at conferences worldwide. Reach Don on Twitter at @concentratedDon, or on Facebook at Facebook.com/ConcentratedDon.

comments powered by Disqus
Most   Popular