如何用PowerShell获取并关闭指定标题的Windows文件资源管理器窗口
按窗口标题关闭单个文件资源管理器窗口的解决方案
问题根源
(New-Object -ComObject Shell.Application).Windows() 仅能枚举集成了IE浏览器控件的资源管理器窗口(比如打开FTP、网页的窗口),普通文件夹窗口不会被纳入枚举范围,因此会出现符合条件的窗口漏返回的情况。
解决方法:调用Windows API枚举并关闭目标窗口
通过PowerShell调用User32.dll的系统API,可以完整枚举所有顶层窗口,筛选出隶属于explorer.exe的窗口,再匹配标题精准关闭。
完整实现代码
Add-Type @" using System; using System.Runtime.InteropServices; public class WindowUtils { [DllImport("user32.dll")] public static extern bool EnumWindows(EnumWindowsProc enumProc, IntPtr lParam); [DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId); [DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern int GetWindowText(IntPtr hWnd, System.Text.StringBuilder lpString, int nMaxCount); [DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr hWnd); [DllImport("user32.dll")] public static extern bool PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam); public delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam); public const uint WM_CLOSE = 0x0010; } "@ # 存储匹配到的窗口句柄 $targetWindows = @() # 枚举所有可见窗口,筛选目标窗口 [WindowUtils]::EnumWindows({ param($hWnd, $lParam) if ([WindowUtils]::IsWindowVisible($hWnd)) { [WindowUtils]::GetWindowThreadProcessId($hWnd, [ref]$pid) $process = Get-Process -Id $pid -ErrorAction SilentlyContinue if ($process -and $process.Name -eq "explorer") { $sb = New-Object System.Text.StringBuilder(256) [WindowUtils]::GetWindowText($hWnd, $sb, $sb.Capacity) $windowTitle = $sb.ToString() # 替换为你需要匹配的标题关键词,比如"恢复网络连接" if ($windowTitle -like "*HFS*") { $targetWindows += $hWnd } } } return $true }, [IntPtr]::Zero) # 关闭所有匹配到的窗口 foreach ($hWnd in $targetWindows) { [WindowUtils]::PostMessage($hWnd, [WindowUtils]::WM_CLOSE, [IntPtr]::Zero, [IntPtr]::Zero) Write-Host "已关闭标题包含'HFS'的资源管理器窗口" }
代码说明
EnumWindows:遍历系统中所有顶层窗口GetWindowThreadProcessId:获取窗口所属进程ID,仅保留explorer.exe的窗口GetWindowText:读取窗口标题,匹配指定关键词PostMessage:发送WM_CLOSE消息关闭窗口,相当于手动点击关闭按钮,不会影响其他资源管理器窗口或整个explorer.exe进程
使用示例
如果要关闭标题包含“恢复网络连接”的窗口,只需将代码中的$windowTitle -like "*HFS*"修改为$windowTitle -like "*恢复网络连接*"即可。
内容的提问来源于stack exchange,提问作者Lawrence
相关产品推荐
相关产品推荐

