Jump to content

How to get parent path in .bat?


Recommended Posts

As we know %~dp0 is the location of current script,so how to get the parent path of current script?

For example:

C:\Documents and Settings\Administrator\Desktop\myfolder

is the current script dir,and i want to get the parent path(C:\Documents and Settings\Administrator\Desktop), what's the syntax?

Link to comment
Share on other sites


still not working

the script

Set InstPath = %~dp0

Set InstPath2 = "%InstPath%\.."

echo %InstPath2%

pause

and the output

C:\Documents and Settings\Administrator\Desktop>Set InstPath = C:\Documents and

Settings\Administrator\Desktop\

C:\Documents and Settings\Administrator\Desktop>Set InstPath2 = "\.."

C:\Documents and Settings\Administrator\Desktop>echo

ECHO is on.

C:\Documents and Settings\Administrator\Desktop>pause

Press any key to continue . . .

Link to comment
Share on other sites

As we know %~dp0 is the location of current script,so how to get the parent path of current script?

For example:

C:\Documents and Settings\Administrator\Desktop\myfolder

is the current script dir,and i want to get the parent path(C:\Documents and Settings\Administrator\Desktop), what's the syntax?

You could do something like that...

SET CurrDir=%CD%
CD..
SET InstPath=%CD%
CD %CurrDir%

:hello:

Link to comment
Share on other sites

%cd% is a poor method to rely on for being the scripts directory as it is the current (working) directory. A batch file called from the registry, as RunOnceEx does, will return C:\ as the current directory.

The best solution was mentioned earlier but %~dp0 has a trailing backslash included, so adding another backslash made it fail. Add the below into a batch file and run it and you will show your solution.

@echo off
cd /d c:\
echo.
echo Current Working directory is : "%cd%"
echo.
echo Script directory is : "%~dp0"
echo.
echo Parent of Script directory is : "%~dp0..\"
echo.
pause
REM ~ Open explorer in the script's parent directory.
explorer.exe "%~dp0..\"

Edited by MHz
Link to comment
Share on other sites

Try this VBS script it start a cmd promt that passes the Current Directory to it.

Save As ComspecTest.VBS

Dim CD, Act : Set Act = CreateObject("Wscript.Shell") : CD = Act.CurrentDirectory

Act.Run("%Comspec% /c Echo Off && CLS && Color 9e && mode 75,7 && Title Test CDset CD=%" &_

CD & "% && Echo %CD% && Echo %UserName% && set /p = It Worked, Press Any Key To Close")

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...