Bringing Window in the Foreground

by Feb 5, 2016

PowerShell can use Add-Type to access internal Windows API functions. This way, it is easy to bring any process window into the foreground. Here is the function you need:

#requires -Version 2
function Show-Process($Process, [Switch]$Maximize)
  $sig = '
    [DllImport("user32.dll")] public static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow)
    [DllImport("user32.dll")] public static extern int SetForegroundWindow(IntPtr hwnd)
  if ($Maximize) { $Mode = 3 } else { $Mode = 4 }
  $type = Add-Type -MemberDefinition $sig -Name WindowAPI -PassThru
  $hwnd = $process.MainWindowHandle
  $null = $type::ShowWindowAsync($hwnd, $Mode)
  $null = $type::SetForegroundWindow($hwnd) 

To test-drive Show-Process, here is a sample code on how to use it:

# launch Notepad minimized, then make it visible
$notepad = Start-Process notepad -WindowStyle Minimized -PassThru
Start-Sleep -Seconds 2
Show-Process -Process $notepad
# switch back to PowerShell, maximized
Start-Sleep -Seconds 2
Show-Process -Process (Get-Process -Id $PID) -Maximize
# switch back to Notepad, maximized
Start-Sleep -Seconds 2
Show-Process -Process $notepad -Maximize
# switch back to PowerShell, normal window
Start-Sleep -Seconds 2
Show-Process -Process (Get-Process -Id $PID)


Throughout this month, we’d like to point you to three awesome community-driven global PowerShell events taking place this year:

Europe: April 20-22: 3-day PowerShell Conference EU in Hannover, Germany, with more than 30+ speakers including Jeffrey Snover and Bruce Payette, and 60+ sessions:

Asia: October 21-22: 2-day PowerShell Conference Asia in Singapore. Watch latest announcements at

North America: April 4-6: 3-day PowerShell and DevOps Global Summit in Bellevue, WA, USA with 20+ speakers including many PowerShell Team members:

All events have limited seats available so you may want to register early.

Twitter This Tip! ReTweet this Tip!