我想关闭所有桌面应用程序。
关闭所有桌面应用程序。
关闭所有应用程序。
关闭所有程序。

import os
import subprocess

print("正在关闭所有桌面应用程序...")

caller_pid = os.getpid()

powershell_script = r'''
$excludeNames = @(
    "explorer",
    "ShellExperienceHost",
    "StartMenuExperienceHost",
    "SearchHost",
    "TextInputHost",
    "ApplicationFrameHost",
    "SystemSettings",

    "cmd",
    "powershell",
    "pwsh",
    "WindowsTerminal",
    "conhost",

    "python",
    "pythonw"
)

$excludeKeywords = @(
    "执行机器人"
)

$protectedPids = New-Object 'System.Collections.Generic.HashSet[int]'

function Add-ProtectedProcessTree {
    param([int]$ProcessId)

    while ($ProcessId -gt 0) {
        [void]$protectedPids.Add($ProcessId)

        try {
            $p = Get-CimInstance Win32_Process -Filter "ProcessId = $ProcessId"
            if ($null -eq $p -or $null -eq $p.ParentProcessId) {
                break
            }

            $ProcessId = [int]$p.ParentProcessId
        } catch {
            break
        }
    }
}

function Test-ExcludedByKeyword {
    param($Process)

    foreach ($keyword in $excludeKeywords) {
        if ($Process.ProcessName -like "*$keyword*") {
            return $true
        }

        if ($Process.MainWindowTitle -like "*$keyword*") {
            return $true
        }
    }

    return $false
}

# 保护当前 PowerShell
Add-ProtectedProcessTree -ProcessId $PID

# 保护调用它的 Python/主控进程
$callerPid = [int]$env:CALLER_PID
Add-ProtectedProcessTree -ProcessId $callerPid

Get-Process |
Where-Object {
    $_.MainWindowHandle -ne 0 -and
    -not $protectedPids.Contains([int]$_.Id) -and
    $excludeNames -notcontains $_.ProcessName -and
    -not (Test-ExcludedByKeyword -Process $_)
} |
ForEach-Object {
    try {
        $_.CloseMainWindow() | Out-Null
    } catch {}
}

$forceCloseNames = @(
    "CalculatorApp",
    "WindowsCalculator",
    "Music.UI",
    "Microsoft.Media.Player",
    "wmplayer"
)

foreach ($name in $forceCloseNames) {
    try {
        Get-Process -Name $name -ErrorAction SilentlyContinue |
        Where-Object {
            -not $protectedPids.Contains([int]$_.Id)
        } |
        Stop-Process -Force -ErrorAction SilentlyContinue
    } catch {}
}

'''

env = os.environ.copy()
env["CALLER_PID"] = str(caller_pid)

subprocess.run(
    ["powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", powershell_script],
    stdout=subprocess.DEVNULL,
    stderr=subprocess.DEVNULL,
    env=env
)

result = "所有桌面应用程序已尝试关闭，已排除包含执行机器人的程序"

print(result)

