Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
169 views
in Technique[技术] by (71.8m points)

How do I find the current directory of a batch file, and then use it for the path?

I have a batch file that I intend to distribute to our customers to run a software task.

We distribute them as a folder or .zip with the files inside. Inside, there is the batch files and another folder with the files needed to run the batch.

Normally, when you make a batch, you type the path where the files are. But I won't know where the files are. The files will still be kept inside the master folder, but I need to have the batch find that folder to run the files.

So for example: If they have the master folder on the desktop and they run it, it would need to be something like "C:UsersUsernameDesktop" to run. You would have the batch CD to that location.

But what if they run it from documents? I don't know the username, so I have to somehow have the batch find this. Any code and/or instructions would be great.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There is no need to know where the files are, because when you launch a bat file the working directory is the directory where it was launched (the "master folder"), so if you have this structure:

.mydocumentsfoldermybat.bat
.mydocumentsfoldersubfolderfile.txt

And the user starts the "mybat.bat", the working directory is ".mydocumentsfolder", so you only need to write the subfolder name in your script:

@Echo OFF
REM Do anything with ".SubfolderFile1.txt"
PUSHD ".Subfolder"
Type "File1.txt"
Pause&Exit

Anyway, the working directory is stored in the "%CD%" variable, and the directory where the bat was launched is stored on the argument 0. Then if you want to know the working directory on any computer you can do:

@Echo OFF
Echo Launch dir: "%~dp0"
Echo Current dir: "%CD%"
Pause&Exit

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...