獲取文件夾下所有文件信息并保存到當前目錄下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.