batch script if user press Ctrl+C do a command before exiting

后端 未结 5 807
闹比i
闹比i 2020-12-19 07:43

I wrote a script which is doing net use at the beginning and net use /DELETE at the end.

But if user decides to press Ctrl +

5条回答
  •  攒了一身酷
    2020-12-19 08:21

    My idea is similar to dbenham's. Took me forever to figure out how to minimize the current console window though. I banged my head against the wall trying to get the cmd window not to ignore an Alt+Space keypress using Wscript.Shell's .SendKeys method. Finally I turned to PowerShell to handle minimizing and restoring the working window.

    The advantage to this over dbenham's is that you'll inevitably have some rectal-cranially inverted user who gets bored with the running of your script and terminates it with the red X. dbenham's won't catch that, but mine should.

    @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
    

提交回复
热议问题