≡ Menu

Get active window on desktop using PowerShell

In today’s post, I want to show how to know what is the active window on Desktop.  I came across this requirement when I want to determine, what is the application user is currently using. There is no PowerShell CMDLET that can do this straight away, so we need to rely on a bit of C# coding to achieve this.

The user32.dll DLL provides function called GetForegroundWindow which provides the window handle of active application/process. We can find the process name by Get-Process with returned window handle.


Add-Type @"
  using System;
  using System.Runtime.InteropServices;
  public class UserWindows {
    public static extern IntPtr GetForegroundWindow();
try {            
$ActiveHandle = [Windows]::GetForegroundWindow()            
$Process = Get-Process | ? {$_.MainWindowHandle -eq $activeHandle}            
$Process | Select ProcessName, @{Name="AppTitle";Expression= {($_.MainWindowTitle)}}            
} catch {            
 Write-Error "Failed to get active Window details. More Info: $_"            


You can download this script from Technet Gallery as well.

Comments on this entry are closed.

  • Jon September 14, 2014, 4:26 am

    Great code, just one problem:

    public class UserWindows

    Then here:
    $ActiveHandle = [Windows]::GetForegroundWindow()

    Change to:
    $ActiveHandle = [UserWindows]::GetForegroundWindow()

    And then it works like a charm 🙂

  • Carsten September 22, 2018, 11:14 pm

    Nice code, but quite useless.
    If you start the script, then the focus is not longer on the original window.

    • MH February 4, 2019, 9:58 pm

      Run it with a keyboard shortcut.

    • Wintel Rocks February 16, 2019, 5:54 pm

      You need to run as a scheduled job under current logged on user.

      • Master Lamps December 8, 2019, 4:06 am

        Thanks for the script. And especially Carsten! You made my day!

  • Mohamed March 9, 2021, 1:07 am


  • Doug November 4, 2021, 10:52 pm

    Thanks! This is still works in Windows 11, over seven years after the original post. I needed to make the public class change Jon mentioned. I added a loop, that appends to an array, and exports to a csv resulting in a nice little activity log with no overhead.
    (definitely not useless…)
    For some reason explorer.exe doesn’t register and returns a null value.