Windows 10

Batch File To Get Current Directory

In this tutorial, we’ll demonstrate two reliable methods for retrieving the current directory path within a Windows batch file. This can be useful in scripting scenarios where you need to work with relative file paths, logs, or automate file operations.

Batch files allow you to automate DOS (Disk Operating System) commands, streamlining routine system tasks and configurations.
 

🧪 Example 1: Get the Script’s Directory Using %~dp0

To get the directory of the currently running batch file, use the special syntax %~dp0. This is particularly useful when your script needs to reference files located in the same directory as the batch file itself.

@echo off
echo Script is located at: %~dp0

🧾 Output Example:

Script is located at: C:\Users\StackHowTo\
  • echo %~dp0 returns the drive and path of the batch file.
  • echo %~f0 returns the full path including the filename of the batch file:
@echo off
echo Full script path: %~f0
🧪 Example 2: Get the Current Working Directory Using %CD%

If you need to obtain the current working directory (i.e., the folder from which the script is run), use the built-in read-only environment variable %CD%.

@echo off
set currentDir=%CD%
echo Current working directory: %currentDir%

🧾 Output Example:

Current working directory: C:\Users\StackHowTo\
🔍 Summary
Method Returns Use Case
%~dp0 Path of the batch file location Referencing script-relative paths
%~f0 Full path and filename of the batch file Logging script identity
%CD% Current working directory Contextual directory during execution

 

Leave a Reply

Your email address will not be published. Required fields are marked *