flyingbird013
flyingbird013

Reputation: 476

How to get path of file with batch

I have a batch file that is stored in the c:\data\profile\script.bat directory. My script.dat contains :

@echo off
echo %~dp0%
pause

If I run it, will display on the screen c:\data\profile\. but that's not what I want. I want to display on the screen c:\data\. for that, I have change my batch contains to :

@echo off
echo %~dp0:~0,8%
pause

then I run the file , but the screen only displays c:\data\profile\:~0,8. please let me know how to do it?

Upvotes: 1

Views: 81

Answers (3)

MC ND
MC ND

Reputation: 70971

If you need to retrieve the parent (.. is the reference to the parent folder) of the folder that contains the batch file (%~dp0), then your batch file could be something like

@echo off
    setlocal enableextensions disabledelayedexpansion
    for %%a in ("%~dp0\..\") do echo %~fa
    pause

Upvotes: 1

MichaelS
MichaelS

Reputation: 6042

How about this:

@ECHO OFF
PUSHD
CD ..
ECHO %CD%
POPD
PAUSE

Your code will work if you modify it like this:

@echo off
set tempPath=%~dp0
echo %tempPath:~0,8%
pause

Upvotes: 1

npocmaka
npocmaka

Reputation: 57332

I want explicitly one level up->

@echo off
set "the_folder=%~dp0"
for %%# in ("%the_folder:~0,-1%") do set "the_folder=%%~dp#"
echo %the_folder%

if you want the first folder in the path:

@echo off
for /f "tokens=2 delims=\" %%# in ("%~dp0") do set "first_folder=%~d0\%%#"
echo %first_folder%

Upvotes: 1

Related Questions