当前位置 : 主页 > 编程语言 > 批处理 >

Windows批处理更改当前工作路径的BAT

来源:互联网 收集:自由互联 发布时间:2020-11-06
获取文件夹下所有文件信息并保存到当前目录下test.txt中的cmd命令: dir /s /b *.* test.txt 保存为test.bat文件,然后双击test.bat后就会在该文件夹目录下生产test.txt,里面会包含所有文件的路

获取文件夹下所有文件信息并保存到当前目录下test.txt中的cmd命令:

dir /s /b *.* > test.txt

保存为test.bat文件,然后双击test.bat后就会在该文件夹目录下生产test.txt,里面会包含所有文件的路径信息。
打开任务计划程序中,创建新的基本任务,安装步骤创建并把启动程序设置成test.bat
右键点击该任务运行,看是否能成功运行test.bat
此处就出现问题了:显示该计划任务已经执行完成,但是你会发现在刚刚文件夹的路径下并没有生成test.txt这个文件。
然后尝试修改test.txt的路径信息,用绝对路径,然后再次运行计划任务

dir /s /b *.* > D:\test\test.txt

依然有问题:虽然test.txt文件确实生成了,但是里面的文件信息并不是当前文件夹下的,而是windows\system32下的文件信息,比如:C:\WINDOWS\system32\0409等等
问题点在于当前工作路径,系统计划任务时候默认的当前工作路径是C:\WINDOWS\system32,所以显示的是C:\WINDOWS\system32下面的文件信息
修改当前工作路径:在bat文件中加入一行,先把bat所在的目录设置成当前工作路径

cd /d %~dp0
dir /s /b *.* > test.txt 

这样一来就完美解决了此问题,计划任务能被完美执行下来去获取当前文件夹下所有文件信息。

如何使用批处理文件更改当前工作目录

I need some help in writing a batch file. I have a path stored in a variable root as follows:

set root=D:\Work\Root

Then I am changing my working directory to this root as follows:

cd %root%

When I execute this batch file from anywhere on the D drive this is done successfully. But when I execute the same batch file from some other drive, cd %root% doesn't work.

Is there a way I can get the drive letter from the root variable? I can then change the current directory to this drive first and then cd %root% shall work.

网友评论