PowerShell Ezine, Logon Scripts

Guy's Scripting Ezine 120 - SendKeys

Guy's Scripting Ezine 120 - SendKeys


This Week's Secret

Whenever I review my previous Ezines it always surprises me which ezines are the most popular.  The way I judge popularity is by the number of page hits each ezine receives.  Consistently, SendKeys featured in Ezine 26, wins the popularity stakes by a country mile.  It is because of the level of interest that I am revisiting this topic, in particular I want to be clear when to use SendKeys and when to seek alternative commands.

This Week's Mission

This week I want to put VBScript's SendKeys method into perspective.  As the name indicates, this method literally sends keyboard keystrokes to the interface which is in focus when the script runs.  I suggest that SendKeys has the following three scenarios when it will assist your scripts.

1) SendKeys is great if you just want to have a bit of fun; it's ideal for practising your scripting techniques in a harmless but enjoyable manner.  For example, when you are learning how to open programs such as notepad, with a VBScript, you want some action, therefore you decide to send key strokes to notepad programmatically.

2) SendKeys is handy strategy when you are at an intermediate stage in your scripting project.  You suspect that your script needs some smart scripting switches or program commands, but you just cannot find them.  As a stop-gap measure, until you can research something better, you fall back on SendKeys to issue instructions as though you were typing them at the keyboard.

3) SendKeys as a last resort.  When all else fails, hours of research fails to find that fancy switch, you turn to SendKeys in desperation.  In these circumstances and for the short term, SendKeys will enable you to fulfil your objective, albeit with risky commands.

Professional script writers don't trust SendKeys.  The reason is because the results of sending keystrokes to applications are unpredictable and potentially catastrophic.  Even if no users are involved, factors may change over time and SendKeys instructions may be delivering their keystrokes to entirely the wrong window.  99% of the time such an error will just result in a routine script failure, but there is a slim chance that the keystrokes could cripple the server, or wipe a database.  Professionals would not risk their reputation on SendKeys. 

The only way to see what SendKeys has to offer is to experiment with an example or two.  As a bonus we can use SendKeys as a vehicle to learn valuable techniques, which you can employ in other VBScripts, for example the Set command and the Shell object.

Guy Recommends:  A Free Trial of the Network Performance Monitor (NPM)Review of Orion NPM v11.5 v11.5

SolarWinds' Orion performance monitor will help you discover what's happening on your network.  This utility will also guide you through troubleshooting; the dashboard will indicate whether the root cause is a broken link, faulty equipment or resource overload.

What I like best is the way NPM suggests solutions to network problems.  Its also has the ability to monitor the health of individual VMware virtual machines.  If you are interested in troubleshooting, and creating network maps, then I recommend that you try NPM now.

Download a free trial of Solarwinds' Network Performance Monitor

SendKeys Methodology

The methodology is to create our shell object then apply the sendkeys method followed by the keystrokes as a string.  Note the placement of both the brackets and of the speech marks.  You could start with typing these commands into notepad and saving the resultant file with a .vbs extension.  Once you have created Example 1, double click your file and observe SendKeys in action.

set objShell = WScript.CreateObject("WScript.Shell")  

Once you have created the shell object then you can send keystrokes to objShell.  However, to be effective, we need our script to launch an application such as notepad or the cmd prompt.

set objShell = WScript.CreateObject("WScript.Shell")

Now we are ready to start sending keys to the CMD prompt session.  In this example we will merely execute a simple "dir" instruction, meaning list the directory contents.

set objShell = WScript.CreateObject("WScript.Shell")
objShell.SendKeys "dir"

Here is the full script with a few extras such as sleep delays, and a final command to exit the cmd prompt application and close the dos box.

Example 1 - VBScript to issue DIR command in a CMD box

' SendKeys.vbs  Example Script
' VBScript to send keyboard strokes to command prompt
' Guy Thomas
' http://computerperformance.co.uk/
' Version 2.1 - August 2006
' --------------------------------------------------------'
Option Explicit

Dim objShell, WshShell
set objShell = CreateObject("WScript.Shell")
WScript.Sleep 500
objShell.SendKeys "dir"
objShell.SendKeys "{Enter}"
WScript.Sleep 3500
objShell.SendKeys "Exit"
objShell.SendKeys "{Enter}"


'  End of SendKeys Example Script

VBScript Learning Points

Note 1:  My use of Sleep to pause the script is contentious.  The reason that I employ this delay to help you trace and understand what is happening.  Professionals say, rightly, that in production scripts you should avoid Sleep commands and instead, let the program handle the timing with their own default routines.  In a nutshell, there is rarely any need for Sleep commands in production scripts.

Note 2:  The Script invokes CMD's own instruction to close, e.g. objShell "Exit".  Observe that the script still needs a carriage return sequence: objShell.SendKeys "{Enter}".  See more special SendKeys instructions at the end of the ezine.

Note 3:  Furthermore, pay special attention to the curly brackets around "{Enter}"

Recommended: Solarwinds' Permissions Analyzer - Free Active Directory ToolFree Permissions Analyzer for Active Directory

I like the Permissions Analyzer because it enables me to see WHO has permissions to do WHAT at a glance.  When you launch this tool it analyzes a users effective NTFS permissions for a specific file or folder, and takes into account network share access, then displays the results in a nifty desktop dashboard!

Think of all the frustration that this free SolarWinds utility saves when you are troubleshooting authorization problems for user's access to a resource.  Give this permissions monitor a try - it's free!

Download SolarWinds' Free Permissions Analyser - Active Directory Tool

Example 2 - VBScript SendKeys, Binocular Vision

Variation ' set WshShell = WScript.CreateObject("WScript.Shell"). 

By analysing this variation of Example 1, we gain what I call binocular vision. Question: is the tiny word 'set' important?  The answer is yes 'set' is crucial and no, you must not change 'set' to any other verb.

WshShell or objShell what is the difference.  Nothing.  Just a matter of personal choice, which name you use for your, observe how I declare employ Option Explicit to force me to declare all my variables. 

In your scripts, will you use WScript.CreateObject or just plain CreateObject.  I stick with CreateObject because it's shorter, clearer and it always works for me.  Purists may argue that you employ the longer WScript.CreateObject.

' SendKeysSub.vbs  Example Script
' VBScript to send keyboard strokes to command prompt
' Guy Thomas
' http://computerperformance.co.uk/
' Version 3.2 - August 2006
' --------------------------------------------------------'
Option Explicit

Dim objShell, WshShell, intSleep
intSleep = 3500
' set objShell = CreateObject("WScript.Shell")
set WshShell = WScript.CreateObject("WScript.Shell")
WScript.Sleep 500
WshShell.SendKeys "dir"
Call GuyClose
WshShell.SendKeys "Exit"
Call GuyClose

sub GuyClose ()
WScript.Sleep intSleep
WshShell.SendKeys "{Enter}"
WScript.Sleep 200
End Sub

'  End of SendKeys Example Script

Note 1:  I added the variable intSleep so that I can control the pauses between instructions from one place.  Incidentally, a value of 1000 for intSleep means wait one second.

Note 2:  Trace the sub-routine.  Shamelessly, I rarely miss a chance to add a sub-routine to handle repetitive command sequences.  Examine the brackets (), the End Sub, and especially how I call the routine.

Note 3:  For this script I followed through and chose WshShell instead of objShell.  As I mentioned earlier, you can choose what ever name you like for the names of your variables.

Guy Recommends: Tools4ever's UMRAUMRA The User Management Resource Administrator

Tired of writing scripts? The User Management Resource Administrator solution by Tools4ever offers an alternative to time-consuming manual processes.

It features 100% auto provisioning, Helpdesk Delegation, Connectors to more than 130 systems/applications, Workflow Management, Self Service and many other benefits. Click on the link for more information on UMRA.

Guy's Challenges

Change the value .Sleep time.

Try running other programs, for example .run("NotePad")

Take a view on my sub-routine GuyClose().  My challenge is to rip it out or modify it and thus learn a little about the value of sub-routines.

Useful List of Special SendKeys commands

  • END {END}
  • ENTER {ENTER} or ~
  • ESC {ESC}
  • TAB {TAB}
  • F1 {F1}

See more on Windows 8 Touch Keyboards »

Summary of SendKeys

SendKeys is a useful temporary measure for passing keystrokes to your program.  By all means have some fun and learn this aspect of VBScript.  However, for production scripts always favour more reliable techniques.

See more about VBScript

VBScripts  • Ezines  • WMI  • Logon Scripts  • Tool Kit

Ezine 26 SendKeys  • Ezine 34 Scriptomatic  • Ezine 47 .put  • Ezine 51 Sleep  • Ezine 52 OS

Ezine 77 Scriptomatic  • Ezine 84 AcctInfo  • Ezine 88 Progress bar  • Ezine 89 SendKeys

Ezine 97 Net Time  • Ezine 98 W32 Time  • Ezine 99 Time services  • Ezine 120 Sendkeys

Custom Search

Site Home

Guy Recommends: WMI Monitor and It's Free!Solarwinds WMI Monitor

Windows Management Instrumentation (WMI) is one of the hidden treasures of Microsoft operating systems.

Fortunately, SolarWinds have created the Free WMI Monitor so that you can actually see and understand these gems of operating system information.  Take the guess work out of which WMI counters to use for scripts.

Download your free copy of WMI Monitor

Author: Guy Thomas Copyright © 1999-2016 Computer Performance LTD All rights reserved.

Please report a broken link, or an error to: