批处理脚本如果用户按Ctrl + C在退出前执行命令

时间:2014-11-25 15:02:46

标签: batch-file cmd exit

我写了一个脚本,开头是net use,最后是net use /DELETE

但如果用户决定按 Ctrl + C 并退出脚本,我需要执行net use /DELETE

这可能吗?我无法在谷歌上找到任何东西。

5 个答案:

答案 0 :(得分:13)

当然,只需在新的CMD会话中执行大部分脚本:

@echo off
if "%~1" neq "_start_" (
  net use ...
  cmd /c "%~f0" _start_ %*
  net use /delete ...
  exit /b
)
shift /1
REM rest of script goes here

只要您的控制台窗口保持打开状态,内部cmd会话关闭后,net use /delete命令将始终触发。由于正常运行,用户按下Ctrl-C或致命错误,它可能会关闭 - 最终的net use \delete仍会触发。

答案 1 :(得分:3)

我的想法与dbenham相似。让我永远想知道如何最小化当前的控制台窗口。我试着让cmd窗口不要忽略使用Alt+Space的{​​{1}} Wscript.Shell方法的.SendKeys按键,而是撞在墙上。最后,我转向PowerShell来处理最小化和恢复工作窗口。

这比dbenham的优势在于你不可避免地会有一些直肠颅倒置的用户对你的脚本运行感到厌倦并用红色X终止它.dbenham不会抓住它,但是我应该这样做。

@echo off
setlocal

if "%~1" neq "wrapped" (

    rem :: Map network drive
    net use y: \\computername\c$ >NUL

    rem :: minimize this console
    powershell -windowstyle minimized -command ""

    rem :: relaunch self with "wrapped" argument and wait for completion
    start /wait "" cmd /c %~f0 wrapped

    rem :: After script completes or user interrupts, remove drive mapping and restore window
    net use y: /delete >NUL
    powershell -windowstyle normal -command ""

    goto :EOF

)

:: Main script goes here.
:loop
cls
echo Simulating script execution...
ping -n 2 0.0.0.0 >NUL
goto loop

答案 2 :(得分:1)

有一个非常简单的解决方案。只需写下:

ping -l www."site".com -t 65500>nul
在你的net use / delete命令之前

。打破该命令的唯一方法是按ctrl + c。 例如:

net use "arguments"
ping -l www.google.com -t 65500>nul
net use /delete

这是检测ctrl + c的好方法,但请注意您编写的站点地址,因为它可能会导致该站点崩溃。因此,您应该写一个不寻常的网站的地址,或者您自己的网站(注意:该网站必须存在),如博客或类似内容。

答案 3 :(得分:0)

我不认为这是可能的。在脚本的开头,您可以使用:

net use /delete 2>nul
net use g: \\server\sharename /persistent:no

或者您可以尝试pushd而不是net use ...

If Command Extensions are enabled the PUSHD command accepts
network paths in addition to the normal drive letter and path.
If a network path is specified, PUSHD will create a temporary
drive letter that points to that specified network resource and
then change the current drive and directory, using the newly
defined drive letter.  Temporary drive letters are allocated from
Z: on down, using the first unused drive letter found.

这样,您将始终正确设置映射驱动器。

答案 4 :(得分:-4)

您需要使用陷阱来执行此操作 Traps

trap ctrl_c INT

function ctrl_c() {
        echo "Trapped"
}