The WScript.Shell Class - a way to interact with an active Window via PowerShell
This article has not been completed yet. However, it may already contain helpful Information and therefore it has been published at this stage.
The WScript.Shell class provides a set of useful utilities that greatly expand the range of tasks that can be performed with Windows PowerShell and COM.
- Running applications
- Sending keyboard input to running applications
- Changing the current working directory
- Displaying pop-up message dialog boxes
- ......
The list of available methods and properties is displayed as follows:
# Creating WScript.Shell Object
$wscript = new-object -com wscript.shell
# Displaying all available object properties / methods
$wscript | gm
TypeName: System.__ComObject#{41904400-be18-11d3-a28b-00104bd35090}
Name MemberType Definition
---- ---------- ----------
AppActivate Method bool AppActivate (Variant, Variant)
CreateShortcut Method IDispatch CreateShortcut (string)
Exec Method IWshExec Exec (string)
ExpandEnvironmentStrings Method string ExpandEnvironmentStrings (string)
LogEvent Method bool LogEvent (Variant, string, string)
Popup Method int Popup (string, Variant, Variant, Variant)
RegDelete Method void RegDelete (string)
RegRead Method Variant RegRead (string)
RegWrite Method void RegWrite (string, Variant, Variant)
Run Method int Run (string, Variant, Variant)
SendKeys Method void SendKeys (string, Variant)
Environment ParameterizedProperty IWshEnvironment Environment (Variant) {get}
CurrentDirectory Property string CurrentDirectory () {get} {set}
SpecialFolders Property IWshCollection SpecialFolders () {get}
The power of the WScript.Shell class is best demonstrated through a simple example. The following script launches an application, waits until the application has started to make it the active application (such that the focus is on the application) and then sends some keys and text to the application.
To be honest, I used it to automate the establishment of a VPN connection. I strongly recommend not to store passwords (as done in this code snippet below) in plain text in a script. A good way to handle passwords can be found here - Link
# Start a Process
$ps = Start-Process -PassThru -FilePath "<FilePath>" -WindowStyle "<Normal|Hidden|Minimized|Maximized>"
# Creating WScript.Shell instance
$wshell = New-Object -ComObject wscript.shell
# Wait until activating the target process succeeds.
# Note: You may want to implement a timeout here.
while (-not $wshell.AppActivate($ps.Id)) {
# Waiting for app to start....
# Start-Sleep -MilliSeconds 200
}
$wshell.SendKeys('~')
Sleep 3
$wshell.SendKeys('username')
Sleep 2
$wshell.SendKeys('{TAB}')
Sleep 1
$wshell.SendKeys('password')
References:
How to use the Secret modules - PowerShell Community (microsoft.com)