Converting the Windows Script Host AppActivate Method

Windows PowerShell

Definition: Activates an application window.


The AppActivate method is typically used in conjunction with the SendKeys method; a script writer will use AppActivate to bring a specified window to the forefront, then use SendKeys to send keystrokes to the application running in that window.

As it turns out, Windows PowerShell doesn’t have any built-in way to bring a window to the front. However, you can easily tap into Visual Basic .NET in order to gain this functionality:

[void] [System.Reflection.Assembly]::LoadWithPartialName("'Microsoft.VisualBasic")
[Microsoft.VisualBasic.Interaction]::AppActivate("Test.ps1 - Notepad")

All we’re doing in the first line of code is loading the .NET Framework class Microsoft.VisualBasic. In the second line, we then call Visual Basic’s AppActivate method, passing this method the title of the window that we want to bring to the front. Keep in mind that the window title is not necessarily the file name; we’re talking about the caption that appears in the title bar of the window. Note, too that you do not have to specify the complete title; you only have to provide enough characters to ensure that PowerShell can figure out which window you’re talking about. For example, suppose you only had one open window in which the title begins with the letters Test. In that case, this bit of code will bring that window to the front:

[void] [System.Reflection.Assembly]::LoadWithPartialName("'Microsoft.VisualBasic")

Alternatively, you can reference a window by its process ID. For example, suppose Test.ps1 has a process ID of 1044. In that case, this tiny little script will bring Test.ps1 to the front:

[void] [System.Reflection.Assembly]::LoadWithPartialName("'Microsoft.VisualBasic")

You say you just want to activate the Notepad window, but you aren’t sure of either the exact window title or the process ID? Well, then try this script:

[void] [System.Reflection.Assembly]::LoadWithPartialName("'Microsoft.VisualBasic")
$a = Get-Process | Where-Object {$_.Name -eq "Notepad"}

The key line here is line 2. In that line we use Get-Process and Where-Object to return the sole instance of the Notepad process, storing that returned value in a variable named $a. When we call the AppActivate method we then use the ID property of $a as our method parameter.

See conversions of other Windows Script Host methods and properties.
Return to the VBScript to Windows PowerShell home page