恢复默认工作目录。如果bat文件被突然终止 [英] Restore default working dir if bat file is terminated abruptly

查看:129
本文介绍了恢复默认工作目录。如果bat文件被突然终止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在那里有一个批处理文件的执行过程中,它导航到不同的文件夹方案(说../asdf);在执行结束,将设置当前工作作为从用户名为.bat文件相同的文件夹目录。

I have a scenario where during execution of a batch file, it navigates to a different folder (say to "../asdf"); and at the end of execution it will set the current working dir as the same folder from where the user called the .bat file.

但是,如果用户终止批处理完成之前,在CMD显示当前的工作目录(比如../ ASDF)。

But if the user terminates the batch processing before it is complete, the cmd show the current working dir (say "../asdf").

但在我而言,我需要将工作目录恢复到默认的/ predefined之一。这可能吗?

But in my case, I need to restore the working dir to the default/predefined one. Is it possible?


  • 批处理文件是我写的,所以我可以修改它。

  • CMD通过桌面快捷方式CMD,这是我的控制下打开;所以像工作目录或通过args设置为CMD等属性可以在那里进行。

推荐答案

在您的批处理脚本中使用 SETLOCAL 封装批处理会话的运行环境。如果用户之前终止脚本 CD POPD 返回,脚本仍将退出目录中它开始。这里有一个简单的测试:

In your batch script use setlocal to encapsulate the running environment of your batch session. If the user terminates the script before you cd or popd to return, your script will still exit in the directory in which it started. Here's a brief test:

@echo off
setlocal
pushd c:\Users
cd
exit /b

输出:

C:\Users\me\Desktop>test.bat
c:\Users

C:\Users\me\Desktop>

注意我没有 POPD CD%USERPROFILE%\\桌面,但我最后还是回到了剧本后,我的台式机退出。

Notice I didn't popd or cd %userprofile%\Desktop, but I still ended up back at my Desktop after the script exited.

此外, SETLOCAL 让你从孤立的变量意味着你的批处理脚本之外没有废弃,另外添购您的环境。这只是很好的做法。在控制台输入帮助SETLOCAL 了解更多信息。

Additionally, setlocal keeps you from junking up your environment with orphaned variables that mean nothing outside of your batch script. It's just good practice. At the console, type help setlocal for more info.

这篇关于恢复默认工作目录。如果bat文件被突然终止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆