Skip to content

Instantly share code, notes, and snippets.

@dstreefkerk
Created March 20, 2019 01:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dstreefkerk/3e30fca08fc1b2827ebea3314c2828dd to your computer and use it in GitHub Desktop.
Save dstreefkerk/3e30fca08fc1b2827ebea3314c2828dd to your computer and use it in GitHub Desktop.
Quick little script that's kinda like a browser's "Close other tabs" function, but for Windows apps
# Quick little script that's kinda like a browser's "Close other tabs" function, but for Windows apps
# Drop a reference to this script into your PowerShell profile as follows:
# New-Alias -Name IFM -Value "C:\Scripts\Invoke-Focus.ps1" -Force
#
# USE AT YOUR OWN RISK
#
# Daniel Streefkerk, 2019
#
# If you want it to terminate apps without cleanly closing them, uncomment the last line
# Locate the main user explorer.exe GUI process
$explorer = gwmi -Query 'SELECT * FROM Win32_Process WHERE Name = "explorer.exe"'
# Grab all of the child processes of the above
$explorerChildProcesses = gwmi -Query "SELECT * FROM Win32_Process WHERE ParentProcessId = $($explorer.ProcessId)"
# Pop up a GridView to prompt the user which apps they want to keep open
$keepAlive = $explorerChildProcesses | select ProcessName,ProcessId | Sort-Object -Property ProcessName | Out-GridView -Title 'Choose Processes to KEEP' -PassThru
# Figure out which processes we want to terminate, subtracting the ones the user opted to keep open
$processesToTerminate = Get-Process -Id (($explorerChildProcesses | select ProcessName,ProcessId) | Compare-Object -ReferenceObject $keepAlive -Property ProcessId | Where-Object {$_.SideIndicator -eq '=>'} | select -ExpandProperty ProcessId)
# Try and gracefully prompt the apps to close
$processesToTerminate | % {$_.CloseMainWindow()}
# If the above doesn't work, force the processes to end (uncomment below if you want this functionality)
#$processesToTerminate | Stop-Process -Force
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment