【问题标题】:Execute a series of commands when a batch program is closed关闭批处理程序时执行一系列命令
【发布时间】:2014-12-15 23:10:43
【问题描述】:

因此,我将继续修改我在上一个问题Incrementing FOR loop for each line in a text file (batch) 中描述的程序。

随着我的前进,我正在尝试创建一个仅在程序运行时授予对文本文档的访问权限的部分。为此,我在启动时授予net use 访问权限。但是,我的困境是我不知道任何批处理事件处理程序可以使我的程序运行net use /delete

什么事件或任何批处理命令允许我这样做?

编辑:我发现了一些关于 /wait 命令的信息,但我不知道这将如何帮助我运行 net use /delete 命令。

【问题讨论】:

    标签: batch-file command exit


    【解决方案1】:

    除了net use,您可以使用pushd 和UNC 路径来创建临时网络驱动器映射。例如:

    pushd \\localhost\c$\Users\%username%\Documents
    

    那么无论你popdendlocalexit /b,还是用户用红色X终止脚本,无论如何,临时映射最后都会被删除。

    只要确保你 setlocal 在你的脚本顶部,或者至少在你之前的某个位置 pushd。无论如何,最好将setlocal 放在每个脚本的顶部,紧跟在@echo off 之后,除非您有特定的理由不这样做。


    如果您需要进行身份验证,请使用net usepushd 的组合。使用不带驱动器号的net use,然后使用pushd \\UNC\path && net use \\computername /delete。这是一个更完整的例子:

    @echo off
    setlocal
    
    set "remotePC=minastirith"
    set "user=%remotePC%\adminUser"
    set "pass=Password"
    
    :: establish an authenticated session
    net use \\%remotePC% /user:%user% %pass%
    
    :: pushd and immediately terminate the net use
    pushd \\%remotePC%\share && net use \\%remotePC% /delete
    
    :: The next two commands demonstrate that even though
    :: the session has been disconnected, pushd still has
    :: temporary access.
    cd
    dir
    
    pause
    
    :: When you popd, endlocal, exit /b, or close the window,
    :: there's no longer an authenticated session.  Another
    :: attempt to pushd should result in an error.
    popd
    pushd \\%remotePC%\share
    
    pause
    

    【讨论】:

    • 我应该更具体。我需要访问 \\localhost,那么有没有办法通过 pushd 命令临时授予访问权限? IE。相当于 /USER:username 密码在网络中用于 pushd 吗?
    • 我不明白 \\localhost 在我留下评论时做了什么。我的意思是 \(another_computer_name)
    • @RecentWebDev2000 我添加了一个附加示例,演示如何将net usepushd 结合起来提供临时身份验证。请参阅上面的修改。
    • 谢谢,这正是我需要的!我又摸索了一下,得出的结论是这是最好的解决方案。
    【解决方案2】:

    添加第二批。对用户单击关闭按钮没有帮助(您需要为此编写一个真实的程序)。

    批次1

    Net use etc
    Call Batch2
    Net Use/delete etc
    

    第二批

    Your commands
    

    当批处理 2 终止时,批处理 1 中的其余命令将运行。你需要阅读帮助call /?

    【讨论】:

      猜你喜欢
      • 2013-09-24
      • 2012-01-21
      • 2022-01-03
      • 1970-01-01
      • 2015-11-29
      • 1970-01-01
      • 1970-01-01
      • 2012-08-11
      • 2016-02-08
      相关资源
      最近更新 更多