如果 bat 文件突然终止,则恢复默认工作目录 [英] Restore default working dir if bat file is terminated abruptly
问题描述
我有一个场景,在执行批处理文件期间,它导航到不同的文件夹(比如../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").
但就我而言,我需要将工作目录恢复为默认/预定义的目录.可能吗?
But in my case, I need to restore the working dir to the default/predefined one. Is it possible?
- 批处理文件是我写的,所以我可以修改它.
- CMD 通过我可以控制的 CMD 桌面快捷方式打开;因此可以在那里完成工作目录或将参数传递给 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:UsersmeDesktop>test.bat
c:Users
C:UsersmeDesktop>
请注意,我没有 popd
或 cd %userprofile%Desktop
,但在脚本退出后我还是回到了我的桌面.
Notice I didn't popd
or cd %userprofile%Desktop
, but I still ended up back at my Desktop after the script exited.
此外,setlocal
可防止您使用孤立变量破坏您的环境,这些孤立变量在您的批处理脚本之外没有任何意义.这只是很好的做法.在控制台中,输入 help 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屋!