Notes‎ > ‎

Windows Scripting using WSH

posted Jul 7, 2011 2:12 PM by Amol Kolhe   [ updated Jul 7, 2011 2:23 PM ]
This is my attempt to dabble with WSH or Windows Script Host.

An excellent resource on Windows scripting is located here:
http://www.pctools.com/guides/scripting/id/30/?act=reference

Here's Microsoft's scripting documentation website (its not great, but its free):
http://technet.microsoft.com/en-us/library/bb902776.aspx

Here's a good link about all the options for the popup method:
http://msdn.microsoft.com/en-us/library/x83z1d9f%28VS.85%29.aspx

To skip reading and download the final versions follow these links:

Here's a windows batch file that I used in the past, to launch applications on startup. The first thing it does is locks my workstation, so that I can leave it unattended and go grab a coffee, while my system starts. Next it launches apps in a certain order. So, when I'm back with a coffee, my system is up and ready for me to use it. I don't have to sit and launch applications.

#File: LaunchWorkspace.cmd
rundll32.exe user32.dll,LockWorkStation
C:
cd "%USERPROFILE%\Desktop\Amol\Workspace\Shortcuts\Quick Launch"
"C:\Program Files\Microsoft Office Communicator\communicator.exe"
sleep 10
"C:\Program Files\Microsoft Office\Office12\OUTLOOK.EXE" /recycle
sleep 30
start /MIN Firefox.lnk
sleep 60
start /MIN mintty.lnk
sleep 5
start /MIN SecureCRT.lnk
sleep 5
start KeePass.lnk
start /MIN Notepad2.lnk "%USERPROFILE%\Desktop\Amol\Docs\Notes.txt"
start /MIN explorer "%USERPROFILE%\Desktop\Amol"
start X-Multiwindow.lnk

This worked fine for a long time, until I thought, it might be nicer to not show a cmd window on screen. So, I used a vbs script to launch my cmd script. This will not show the command window at all, and still execute the batch file (that can be so dangerous BTW, imagine someone executing random comands on your system without you ever being able to see a window. Don't use this for illegal purposes!!):

# File: LaunchWorkspace.vbs
Set WshShell = CreateObject("WScript.Shell")
WshShell.Run chr(34) & "C:\bin\LaunchWorkspace.cmd" & Chr(34), 0
Set WshShell = Nothing

This worked nice and fine, but I thought it might be nice to learn some windows scripting.

The basic difference between any unix script and a windows script is return codes. In Windows, Successful execution of a command/script returns 1. Failed execution returns 2

For example, if you want to get user input using an ok/cancel popup, ok will return 1 while cancel will return 2.

Here's a small script, which will track an ok/cancel input from user:

set WshShell = CreateObject("WScript.Shell")
Choice = WshShell.Popup("The computer will be locked in 10 seconds. Press Ok to lock it now or Cancel to avoid locking.", 10, "Title", 65)
msgbox Choice

Here's my final script to launch programs based on my previous batch file, but a bit smarter.



'Filename: LaunchWorkspace.vbs

'launch_workspace_timeout = 15
lock_timeout = 10

Set WshShell = WScript.CreateObject("WScript.Shell")

'Choice = WshShell.Popup("Launching Workspace. Press Ok to continue or Cancel to abort. Operation will continue automatically, in " & launch_workspace_timeout & " seconds.", launch_workspace_timeout, "LaunchWorkspace", 65)
'If Choice = 2 Then
' WScript.Quit
' If I'm not connected to Network, or for any reason, I don't wanna run the script
' I can cancel if I want.
' Otherwise, it will just auto-continue.
'End If

'Choice = WshShell.Popup("Launching Workspace. The computer will be locked in " & lock_timeout & " seconds. Press Ok to lock now. Press Cancel to avoid locking. Press No to abort Launching Workspace.", lock_timeout, "LaunchWorkspace", 65)
'Wscript.Echo Choice
'If Choice = 2 Then
' Do nothing
' Just stop the timeout. And not Lock Workstation.
'Else
' Lock Workstation
' WshShell.Run("rundll32.exe user32.dll,LockWorkStation")
'End If

Choice = WshShell.Popup("The computer will be locked in " & lock_timeout & " seconds. Press Ok to lock now, Cancel to avoid locking. Press No to abort Launching Workspace.", lock_timeout, "LaunchWorkspace: initializing ....", 3)
'This will provide a Yes/No/Cancel Dialog.
'Yes returns 6, No returns 7, Cancel returns 2
'Wscript.Echo Choice
'If Choice = 2 Then
' Do nothing
' Just stop the timeout. And not Lock Workstation.
'Else
' Lock Workstation
' WshShell.Run("rundll32.exe user32.dll,LockWorkStation")
'End If

Select Case Choice
   Case 6  'Yes
       WshShell.Run("rundll32.exe user32.dll,LockWorkStation")
   Case 7  'No
       Result = WshShell.Popup("Aborted Launching Workspace.", 2, "LaunchWorkspace", 0)
       WScript.Quit
   Case 2  'Cancel
       ' Do nothing
       ' Just stop the timeout. And not Lock Workstation.
   Case Else
       WshShell.Run("rundll32.exe user32.dll,LockWorkStation")
End Select

'Run works like this:
'   object.Run(strCommand, [intWindowStyle], [bWaitOnReturn])
'   strCommand is the command to execute
'   [intWindowStyle] is an integer between 0-8 which determines the window state
       '0: No Window, 1: Normal Window, 2: Minimized Window, 3: Maximized Window, etc
'   [bWaitOnReturn] is True/False and determines whether to wait for the command to finish (i.e. Application to close)
'       default is false

' Note: If the application name/path has space in it, then we need to use 3 double quotes before and after instead of 1 double quotes.
WshShell.Run """C:\Program Files\Microsoft Office Communicator\communicator.exe""",1,False
WScript.Sleep(5000)

WshShell.Run """C:\Program Files\Microsoft Office\Office12\OUTLOOK.EXE""" & "/recycle",1,False
WScript.Sleep(5000)

WshShell.Run """C:\Program Files\Mozilla Firefox\firefox.exe""",1,False
WScript.Sleep(50000)

WshShell.Run """C:\Program Files\Notepad2\Notepad2.exe""" & "%USERPROFILE%\Desktop\Amol\Docs\Notes.txt",1,False
WScript.Sleep(5000)

WshShell.Run "explorer" & " %USERPROFILE%\Desktop\Amol",1,False
WScript.Sleep(5000)

WshShell.Run "C:\cygwin\bin\mintty.exe - ",1,False
WScript.Sleep(5000)

'Start X-windows and xterm.
WshShell.Run "C:\cygwin\bin\run.exe /usr/bin/xwin -clipboard -trayicon -logverbose 0 -silent-dup-error -lesspointer -screen 0 @2 -multiwindow",1,False
WScript.Sleep(5000)
WshShell.Run "C:\cygwin\bin\run.exe /usr/bin/xhost +",1,False
WshShell.Run "C:\cygwin\bin\run.exe /usr/bin/xterm",1,False
WScript.Sleep(5000)

'WshShell.Run "C:\cygwin\bin\run.exe /usr/local/bin/mrxvt -ls +showmenu",1,False

Result = WshShell.Popup("Workspace Launch Complete.", 3, "LaunchWorkspace", 0)



Echo
'VBScript Example
WScript.Echo "Hello World!"
WScript.Echo "Hello" & " " & "World!"
WScript.Echo "Hello", "World!"

'JScript Example
WScript.Echo("Hello World!")
WScript.Echo("Hello" + " " + "World!")
WScript.Echo("Hello", "World!")

'VBScript Example
set WshShell = CreateObject("WScript.Shell")
WScript.Echo WshShell.ExpandEnvironmentStrings("%SystemRoot%")
WScript.Echo WshShell.ExpandEnvironmentStrings("%WinDir%")

AppActivate
'VBScript Example
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.AppActivate ("Internet Explorer")

Run
'VBScript Example
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run("%windir%\notepad.exe")
ReturnCode = WshShell.Run("%windir%\notepad.exe", 1, True)

Quit
'VBScript: terminate the current script
WScript.Quit
'JavaScript: terminate the current script with exit code 2
WScript.Quit 2

Sleep
'VBScript Example
WScript.Sleep 2000 'sleep for 2 seconds

'JScript Example
WScript.Sleep(2000) 'sleep for 2 seconds

Send Keys
'VBScript Example
Set WshShell = WScript.CreateObject("WScript.Shell")

WshShell.Run "%windir%\notepad.exe"
WshShell.AppActivate "Notepad"
WshShell.SendKeys "Hello World!"
WshShell.SendKeys "{ENTER}"
WshShell.SendKeys "abc"
WshShell.SendKeys "{CAPSLOCK}"
WshShell.SendKeys "def"

Write to Registry
'VBScript Example
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.RegWrite "HKLM\Test\Value", "Test String", "REG_SZ"
WshShell.RegWrite "HKLM\Test\IntValue", 543, "REG_DWORD"

GetObject
Set MyDocument = GetObject("c:\work\order.doc")
MyDocument.SaveAs "c:\work\order_new.doc"