Created
October 16, 2024 00:56
-
-
Save Calvindd2f/644417e241f7d7ac4d61926064476916 to your computer and use it in GitHub Desktop.
The main function Check-And-Shutdown-WSL does the following: Checks all window titles for "WSL" or "Linux" using the Get-WindowTitles function. If no WSL/Linux windows are found, it checks for running WSL processes. If WSL processes are found but no windows are open, it runs wsl --shutdown. If no WSL windows or processes are found, it reports th…
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function chk_wsl { | |
| Add-Type @" | |
| using System; | |
| using System.Runtime.InteropServices; | |
| public class User32 { | |
| [DllImport("user32.dll")] | |
| public static extern IntPtr GetForegroundWindow(); | |
| [DllImport("user32.dll")] | |
| public static extern int GetWindowText(IntPtr hWnd, System.Text.StringBuilder text, int count); | |
| } | |
| "@ | |
| function Get-WindowTitles { | |
| $titles = @() | |
| $windows = [System.Diagnostics.Process]::GetProcesses() | Where-Object {$_.MainWindowTitle -ne ""} | |
| foreach ($window in $windows) { | |
| $hWnd = $window.MainWindowHandle | |
| $title = New-Object System.Text.StringBuilder 256 | |
| [User32]::GetWindowText($hWnd, $title, 256) | Out-Null | |
| $titles += $title.ToString() | |
| } | |
| return $titles | |
| } | |
| $wslTitles = Get-WindowTitles | Where-Object { $_ -match "WSL|Linux" } | |
| if ($wslTitles.Count -eq 0) { | |
| $wslProcesses = Get-Process | Where-Object { $_.Name -match "wsl|linux" } | |
| if ($wslProcesses.Count -gt 0) { | |
| Write-Host "No WSL windows found, but WSL processes are running. Shutting down WSL..." | |
| wsl --shutdown | |
| Write-Host "WSL has been shut down." | |
| } else { | |
| Write-Host "No WSL windows or processes found. Nothing to shut down." | |
| } | |
| } else { | |
| Write-Host "WSL or Linux windows are currently open. Not shutting down." | |
| } | |
| } | |
| # Call the function | |
| Check-And-Shutdown-WSL |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment