I'm writing a batch file, I need to get the parent folder of this bat file. Is it possibile? NB I mean the parent folder of the batch file not of the current directory of the prompt calling that batch.
Thanks
When you want to go back, type cd - and you will be back where you started.
With a directory, a parent directory is a directory containing the current directory. For example, in the MS-DOS path below, the "Windows" directory is the parent directory of the "System32" directory, and C:\ is the root directory.
If you want to open the file/folder in a new window use CTRL+Click. On the contrary, the "Up" button used to take you one level higher (to the parent) regardless of the means you used to get to that folder (search results, shortcuts, etc.).
The parent folder of a Batch is in the Variable %~dp0
located. Example:
@echo off&setlocal
for %%i in ("%~dp0.") do set "folder=%%~fi"
echo %folder%
Endoro's answer doesn't work for me either but this does. This is what I use myself to do this.
V3
One of these should do the right thing
for %%I in ("%~dp0.") do for %%J in ("%%~dpI.") do set ParentFolderName=%%~nxJ
echo %ParentFolderName%
for %%I in ("%~dp0.") do for %%J in ("%%~dpI.") do set ParentFolderName=%%~dpnxJ
echo %ParentFolderName%
V2:
for %%I in ("%~dp0\.") do set ParentFolderName=%%~nxI
echo %ParentFolderName%
V1:
This one gets the parent directory of the current working directory
for %%I in (..) do set ParentFolderName=%%~nI%%~xI
echo %ParentFolderName%
Reference: For | Microsoft Docs
If you want the folder where the batch file is located, you can assign
SET folder=%~dp0
as mentioned in another answer.
If you want the folder above the location of the batch file, you can assign
SET folder=%~dp0..\
However, this last variable could be inadequate if you plan to show the path to the user. In that case, perphaps it is preferable
FOR %%A IN ("%~dp0.") DO SET folder=%%~dpA
As an example, if you have the following script in C:\Users\Public
@ECHO OFF
ECHO %~dp0
ECHO %~dp0..\
FOR %%A IN ("%~dp0.") DO ECHO %%~dpA
the output will be
C:\Users\Public\
C:\Users\Public\..\
C:\Users\
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With