You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将禁用CMD关闭按钮的PS1脚本转换为单行PowerShell命令

禁用CMD窗口关闭按钮的单行PowerShell命令实现

需求背景

在CMD环境执行DISM操作时,提前关闭CMD窗口会引发问题,需要禁用CMD窗口的关闭按钮。此前通过CMD脚本生成临时PS1文件执行,现需改为无需临时文件的单行PowerShell命令。

单行命令实现

直接在CMD中执行以下命令即可禁用当前窗口的关闭按钮:

powershell -nop -c '$code="using System;using System.Runtime.InteropServices;namespace CloseButtonToggle{internal static class WinAPI{[DllImport(`"kernel32.dll`")]internal static extern IntPtr GetConsoleWindow();[DllImport(`"user32.dll`")][return: MarshalAs(UnmanagedType.Bool)]internal static extern bool DeleteMenu(IntPtr hMenu,uint uPosition,uint uFlags);[DllImport(`"user32.dll`")][return: MarshalAs(UnmanagedType.Bool)]internal static extern bool DrawMenuBar(IntPtr hWnd);[DllImport(`"user32.dll`")]internal static extern IntPtr GetSystemMenu(IntPtr hWnd,[MarshalAs(UnmanagedType.Bool)]bool bRevert);const uint SC_CLOSE=0xf060;const uint MF_BYCOMMAND=0;internal static void ChangeCurrentState(bool state){IntPtr hMenu=GetSystemMenu(GetConsoleWindow(),state);DeleteMenu(hMenu,SC_CLOSE,MF_BYCOMMAND);DrawMenuBar(GetConsoleWindow());}}public static class Status{public static void Disable(){WinAPI.ChangeCurrentState(false);}}}";Add-Type $code;[CloseButtonToggle.Status]::Disable()'

命令说明

  • 参数解析:
    • -nop:禁用PowerShell配置文件加载,提升执行效率
    • -c:指定要执行的PowerShell命令字符串
  • 核心逻辑:
    • 将原C#代码压缩为单行字符串,通过Add-Type动态编译
    • 调用编译后的类方法,调用Win32 API删除控制台窗口的关闭菜单并刷新菜单栏

恢复关闭按钮(可选)

若需重新启用关闭按钮,只需修改命令中的状态参数,执行以下命令:

powershell -nop -c '$code="using System;using System.Runtime.InteropServices;namespace CloseButtonToggle{internal static class WinAPI{[DllImport(`"kernel32.dll`")]internal static extern IntPtr GetConsoleWindow();[DllImport(`"user32.dll`")][return: MarshalAs(UnmanagedType.Bool)]internal static extern bool DeleteMenu(IntPtr hMenu,uint uPosition,uint uFlags);[DllImport(`"user32.dll`")][return: MarshalAs(UnmanagedType.Bool)]internal static extern bool DrawMenuBar(IntPtr hWnd);[DllImport(`"user32.dll`")]internal static extern IntPtr GetSystemMenu(IntPtr hWnd,[MarshalAs(UnmanagedType.Bool)]bool bRevert);const uint SC_CLOSE=0xf060;const uint MF_BYCOMMAND=0;internal static void ChangeCurrentState(bool state){IntPtr hMenu=GetSystemMenu(GetConsoleWindow(),state);DeleteMenu(hMenu,SC_CLOSE,MF_BYCOMMAND);DrawMenuBar(GetConsoleWindow());}}public static class Status{public static void Enable(){WinAPI.ChangeCurrentState(true);}}}";Add-Type $code;[CloseButtonToggle.Status]::Enable()'

内容的提问来源于stack exchange,提问作者PlayLORD-SysOp

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 17:22:03