Batch Get Script Directory

Batch get script directory

To use any of the following ways, you must know how to create and run the batch files and PowerShell script files. For this article, we have prepared the following PowerShell script and saved it in the testPS.ps1 file to run batch file:

Remember, you may have to update the path of the .bat file in the above script based on what solution to use. Also, don’t forget to enclose the path within double quotes ("") if the directory name contains spaces.

Using %CD Variable

Use the %CD variable to get the batch script’s path in the Windows operating system.

This code was stored in the test.bat file. Here, we used the %CD variable containing the current working directory. We use this solution if the batch file lives in the same directory as the script file; otherwise, we will get the path of the PowerShell script file, not the batch file. For example, the above output is fine because both files (test.bat and testPS.ps1) are in the same directory, but what if we have these two files in different locations? In that case, we can use the following solution.

Using %~dp0 Parameter

Use the %~dp0 parameter to get the batch script’s path in the Windows operating system.

This time, our test.bat and testPS.ps1 files were located at two different locations, E:\Test\Scripts and E:\Test. Here, we used the %~dp0 parameter to retrieve the path of the test.bat file. If you want to remove the final backslash, you can use the :n,m substring syntax as demonstrated below.

In the above examples, you may have noticed that we only got the location where the test.bat file is located, not the file’s name. We can also use the %~nx0 parameter to know the batch file’s name. See the following example:

You can visit this page to dig more about batch parameters.

Using PUSHD Command

Use the PUSHD command to get the directory of the batch script file in the Windows operating system.

This approach is different from the previous ones. For the above code, we used the PUSHD command, which changed the current working directory to the batch file’s directory and pushed the current working directory onto a stack. Once the script is fully executed, the POPD command will be run to return the previous working directory, which we pushed onto the stack.

The D in PUSHD and POPD means Directory.

This method lets the script modify the directory and run other commands before returning to the original directory.

Was this post helpful?

Leave a Reply

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