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
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
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%
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\
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
So this is a bad answer, but I use it more times than I'll admit these days:
powershell -command "(get-item '%~dp0').name" > %temp%\temp_var.txt
set /p parent_folder= < %temp%\temp_var.txt
echo %parent_folder%
pause
Since PowerShell is nearly everywhere these days when it comes to Windows, I abuse it as much as I can.
However, it's bad because it does rely on PowerShell existing within your environment path, and it relies on no other script modifying your temporary storage file between your script writing to it and reading it.