I have a directory path and I want to find a particular file in a directory directly above my path. Similar to the MSBuild command
"$([MSBuild]::GetPathOfFileAbove(filename.ext))"
except in a DOS prompt.
So if my directory path is c:\one\two\three\four
I want to look for filename.ext in c:\one\two\three\four, then in c:\one\two\three, then in c:\one\two, then in c:\one, then in c:, and return the path to the first instance of filename.ext I find. Is that possible in a simple DOS script?
The FOR command only seems to have /r, for searching recursively below the supplied directory path. I've searched everything I can think of and only found solutions for searching subdirectories below a path.
There is no such command. (I doubt, there is one in any language). So you need to climb up the tree by yourself.
Look if the file is in the current folder. If it is, store the folder and break the loop. Else go up one step and loop until you are on the top.
#echo off
:loop
echo ---- current = %cd%
dir /b desired.txt >nul 2>&1 && (set "folder=%cd%" & goto :finish)
if "%cd:~3%" == "" goto :finish
cd..
goto :loop
:finish
echo found file in %folder%
I need to write a script to work in Windows, that when executed will run a command in some of sub-directories, but unfortunately I have never done anything in batch, and I don't know where to start.
With the example structure of folders:
\root
\one
\two
\three
\four
I want the script to enter the specified folders (e.g. only 'one' and 'four') and then run some command inside every child directories of that folders.
If you could provide any help, maybe some basic tutorial or just names of the commands I will need, I would be very grateful.
You can tell the batch to iterate directories:
for /d %i in (C:\temp\*) do ( cd "%i" & *enter your command here* )
Use a percent sign when run directly on the command line, two when run from a batch
In a batch this would look something like this:
#echo off
set back=%cd%
for /d %%i in (C:\temp\*) do (
cd "%%i"
echo current directory:
cd
pause
)
cd %back%
Put the commands you need in the lines between ( and ).
If you replace C:\temp\ with %1 you can tell the batch to take the value of the directory from the first parameter when you call it.
Depending of the amount of directories you then either call the batch for each directory or read them from a list:
for /f %i in (paths.lst) do call yourbatch %i
The paths.lstwill look like this:
C:\
D:\
Y:\
C:\foo
All of this is written from memory, so you might need to add some quotations marks ;-)
Please note that this will only process the first level of directories, that means no child folders of a selected child folder.
You should take a look at this. The command you are looking for is FOR /R. Looks something like this:
FOR /R "C:\SomePath\" %%F IN (.) DO (
some command
)
I like answer of Marged that has been defined as BEST answer (I vote up), but this answer has a big inconvenience.
When DOS command between ( and ) contains some errors, the error message returned by DOS is not very explicit.
For information, this message is
) was unexpected at this time.
To avoid this situation, I propose the following solution :
#echo off
pushd .
for /d %%i in (.\WorkingTime\*.txt) do call :$DoSomething "%%i"
popd
pause
exit /B
::**************************************************
:$DoSomething
::**************************************************
echo current directory: %1
cd %1
echo current directory: %cd%
cd ..
exit /B
The FOR loop call $DoSomething "method" for each directory found passing DIR-NAME has a parameter. Caution: doublequote are passed to %1 parameter in $DoSomething method.
The exit /B command is used to indicate END of method and not END of script.
The result on my PC where I have 2 folders in c:\Temp folder is
D:\#Atos\Prestations>call test.bat
current directory: ".\New folder"
current directory: D:\#Atos\Prestations\New folder
current directory: ".\WorkingTime"
current directory: D:\#Atos\Prestations\WorkingTime
Press any key to continue . . .
Caution: in Margeds answer, usage of cd "%%i" is incorrect when folder is relative (folder with . or ..).
Why, because the script goto first folder and when it is in first folder it request to goto second folder FROM first folder !
On Windows 10 and later, it should be like this:
#echo off
for /D %%G in ("C:\MyFolderToLookIn\*") DO (
echo %%~nxG
)
This will show the name of each folder in "C:\MyFolderToLookIn". Double quotes are required.
If you want to show full path of the folder, change echo %%~nxG with echo %%G
My batch scripts are located in the following directory:
\\test\public\windows\scripts\32\test.bat
I'm trying to get the path of this folder: \test\public\windows\logs
I've tried using %~dp0 in order to get the path of the script, and i've tried:
SET REL_PATH=..\..\
The thing is that it's not showing me this folder.
SET REL_PATH=..\..\
path points to the path according to you, to verify where it is taking from, please make a
echo %CD%
it will tell you the path the system is looking at.
then set the relative path from %CD% to the path of your script.
Please comment if you get stuck after doing this.
For example:
echo %CD%
gives C:\windows\system32
and you want to execute batch file at c:\test\public\windows\scripts\32\test.bat
you will need to do
SET REL_PATH=%CD%\..\..\test\public\windows\scripts\32\
To move to this path do a:
cd /d %REL_PATH%
To solve UNC path do PUSHD and POPD:
#echo off
pushd \\test\public\windows\scripts\32\
REM do your work
call test.bat
popd
Reference: How to run batch file from network share without "UNC path are not supported" message?
Use the PUSHD command when working with network drives. This will assign an unused drive letter to the UNC path so you can navigate it like normal. Then you can use POPD to release it.
For example:
#ECHO OFF
PUSHD "\\test\public\windows\scripts\32"
REM This will be \\test\public\windows
DIR ".\..\..\"
POPD
How can I set a variable with the current location? For instance, if I get in c:\test and want to set the variable to test and if I get inside c:\test\test2 the variable will be set to test2.
I'm thinking about using a for to get inside a lot of folders and check if some file exists, if the correct file exist I want to set the current folder to a variable so I can copy the path and copy the folder.
The main problem deals with copying the rest of the files is the same folder as the .inf file.
The current directory is in the "shadow" variable cd.
You could try
set "var=%cd%"
%~dp0
This expands into the drive & path of the currently running batch file. I usually surround my batch files with something like:
#echo off
pushd %~dp0
...
popd
Edit: It seems I didn't understand the OP. My example gets the location of the currently running script, not the "Current Directory". +1 to jeb.
I think there is a little confussion here. %CD% always have the current directory, so you don't need to add anything to have it. However, by rereading your original question, I think that you need the LAST PART of the current directory, that is, the name of the current location excluding all previous locations. If so, then you may use this:
set i=0
:nextdir
set /a i+=1
for /f "tokens=%i% delims=\" %%a in ("%CD%") do if not "%%a" == "" set lastdir=%%a& goto nextdir
echo Current location: %lastdir%
Is there a way in a Windows batch script to return an absolute path from a value containing a filename and/or relative path?
Given:
"..\"
"..\somefile.txt"
I need the absolute path relative to the batch file.
Example:
"somefile.txt" is located in "C:\Foo\"
"test.bat" is located in "C:\Foo\Bar".
User opens a command window in "C:\Foo" and calls Bar\test.bat ..\somefile.txt
In the batch file "C:\Foo\somefile.txt" would be derived from %1
In batch files, as in standard C programs, argument 0 contains the path to the currently executing script. You can use %~dp0 to get only the path portion of the 0th argument (which is the current script) - this path is always a fully qualified path.
You can also get the fully qualified path of your first argument by using %~f1, but this gives a path according to the current working directory, which is obviously not what you want.
Personally, I often use the %~dp0%~1 idiom in my batch file, which interpret the first argument relative to the path of the executing batch. It does have a shortcoming though: it miserably fails if the first argument is fully-qualified.
If you need to support both relative and absolute paths, you can make use of Frédéric Ménez's solution: temporarily change the current working directory.
Here's an example that'll demonstrate each of these techniques:
#echo off
echo %%~dp0 is "%~dp0"
echo %%0 is "%0"
echo %%~dpnx0 is "%~dpnx0"
echo %%~f1 is "%~f1"
echo %%~dp0%%~1 is "%~dp0%~1"
rem Temporarily change the current working directory, to retrieve a full path
rem to the first parameter
pushd .
cd %~dp0
echo batch-relative %%~f1 is "%~f1"
popd
If you save this as c:\temp\example.bat and the run it from c:\Users\Public as
c:\Users\Public>\temp\example.bat ..\windows
...you'll observe the following output:
%~dp0 is "C:\temp\"
%0 is "\temp\example.bat"
%~dpnx0 is "C:\temp\example.bat"
%~f1 is "C:\Users\windows"
%~dp0%~1 is "C:\temp\..\windows"
batch-relative %~f1 is "C:\Windows"
the documentation for the set of modifiers allowed on a batch argument can be found here:
https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/call
I came across a similar need this morning: how to convert a relative path into an absolute path inside a Windows command script.
The following did the trick:
#echo off
set REL_PATH=..\..\
set ABS_PATH=
rem // Save current directory and change to target directory
pushd %REL_PATH%
rem // Save value of CD variable (current directory)
set ABS_PATH=%CD%
rem // Restore original directory
popd
echo Relative path: %REL_PATH%
echo Maps to path: %ABS_PATH%
Most of these answers seem crazy over complicated and super buggy, here's mine -- it works on any environment variable, no %CD% or PUSHD/POPD, or for /f nonsense -- just plain old batch functions. -- The directory & file don't even have to exist.
CALL :NORMALIZEPATH "..\..\..\foo\bar.txt"
SET BLAH=%RETVAL%
ECHO "%BLAH%"
:: ========== FUNCTIONS ==========
EXIT /B
:NORMALIZEPATH
SET RETVAL=%~f1
EXIT /B
Without having to have another batch file to pass arguments to (and use the argument operators), you can use FOR /F:
FOR /F %%i IN ("..\relativePath") DO echo absolute path: %%~fi
where the i in %%~fi is the variable defined at /F %%i. eg. if you changed that to /F %%a then the last part would be %%~fa.
To do the same thing right at the command prompt (and not in a batch file) replace %% with %...
This is to help fill in the gaps in Adrien Plisson's answer (which should be upvoted as soon as he edits it ;-):
you can also get the fully qualified path of your first argument by using %~f1, but this gives a path according to the current path, which is obviously not what you want.
unfortunately, i don't know how to mix the 2 together...
One can handle %0 and %1 likewise:
%~dpnx0 for fully qualified drive+path+name+extension of the batchfile itself,
%~f0 also suffices;
%~dpnx1 for fully qualified drive+path+name+extension of its first argument [if that's a filename at all],
%~f1 also suffices;
%~f1 will work independent of how you did specify your first argument: with relative paths or with absolute paths (if you don't specify the file's extension when naming %1, it will not be added, even if you use %~dpnx1 -- however.
But how on earth would you name a file on a different drive anyway if you wouldn't give that full path info on the commandline in the first place?
However, %~p0, %~n0, %~nx0 and %~x0 may come in handy, should you be interested in path (without driveletter), filename (without extension), full filename with extension or filename's extension only. But note, while %~p1 and %~n1 will work to find out the path or name of the first argument, %~nx1 and %~x1 will not add+show the extension, unless you used it on the commandline already.
You can also use batch functions for this:
#echo off
setlocal
goto MAIN
::-----------------------------------------------
:: "%~f2" get abs path of %~2.
::"%~fs2" get abs path with short names of %~2.
:setAbsPath
setlocal
set __absPath=%~f2
endlocal && set %1=%__absPath%
goto :eof
::-----------------------------------------------
:MAIN
call :setAbsPath ABS_PATH ..\
echo %ABS_PATH%
endlocal
Small improvement to BrainSlugs83's excellent solution. Generalized to allow naming the output environment variable in the call.
#echo off
setlocal EnableDelayedExpansion
rem Example input value.
set RelativePath=doc\build
rem Resolve path.
call :ResolvePath AbsolutePath %RelativePath%
rem Output result.
echo %AbsolutePath%
rem End.
exit /b
rem === Functions ===
rem Resolve path to absolute.
rem Param 1: Name of output variable.
rem Param 2: Path to resolve.
rem Return: Resolved absolute path.
:ResolvePath
set %1=%~dpfn2
exit /b
If run from C:\project output is:
C:\project\doc\build
I have not seen many solutions to this problem. Some solutions make use of directory traversal using CD and others make use of batch functions. My personal preference has been for batch functions and in particular, the MakeAbsolute function as provided by DosTips.
The function has some real benefits, primarily that it does not change your current working directory and secondly that the paths being evaluated don't even have to exist. You can find some helpful tips on how to use the function here too.
Here is an example script and its outputs:
#echo off
set scriptpath=%~dp0
set siblingfile=sibling.bat
set siblingfolder=sibling\
set fnwsfolder=folder name with spaces\
set descendantfolder=sibling\descendant\
set ancestorfolder=..\..\
set cousinfolder=..\uncle\cousin
call:MakeAbsolute siblingfile "%scriptpath%"
call:MakeAbsolute siblingfolder "%scriptpath%"
call:MakeAbsolute fnwsfolder "%scriptpath%"
call:MakeAbsolute descendantfolder "%scriptpath%"
call:MakeAbsolute ancestorfolder "%scriptpath%"
call:MakeAbsolute cousinfolder "%scriptpath%"
echo scriptpath: %scriptpath%
echo siblingfile: %siblingfile%
echo siblingfolder: %siblingfolder%
echo fnwsfolder: %fnwsfolder%
echo descendantfolder: %descendantfolder%
echo ancestorfolder: %ancestorfolder%
echo cousinfolder: %cousinfolder%
GOTO:EOF
::----------------------------------------------------------------------------------
:: Function declarations
:: Handy to read http://www.dostips.com/DtTutoFunctions.php for how dos functions
:: work.
::----------------------------------------------------------------------------------
:MakeAbsolute file base -- makes a file name absolute considering a base path
:: -- file [in,out] - variable with file name to be converted, or file name itself for result in stdout
:: -- base [in,opt] - base path, leave blank for current directory
:$created 20060101 :$changed 20080219 :$categories Path
:$source http://www.dostips.com
SETLOCAL ENABLEDELAYEDEXPANSION
set "src=%~1"
if defined %1 set "src=!%~1!"
set "bas=%~2"
if not defined bas set "bas=%cd%"
for /f "tokens=*" %%a in ("%bas%.\%src%") do set "src=%%~fa"
( ENDLOCAL & REM RETURN VALUES
IF defined %1 (SET %~1=%src%) ELSE ECHO.%src%
)
EXIT /b
And the output:
C:\Users\dayneo\Documents>myscript
scriptpath: C:\Users\dayneo\Documents\
siblingfile: C:\Users\dayneo\Documents\sibling.bat
siblingfolder: C:\Users\dayneo\Documents\sibling\
fnwsfolder: C:\Users\dayneo\Documents\folder name with spaces\
descendantfolder: C:\Users\dayneo\Documents\sibling\descendant\
ancestorfolder: C:\Users\
cousinfolder: C:\Users\dayneo\uncle\cousin
I hope this helps... It sure helped me :)
P.S. Thanks again to DosTips! You rock!
You can just concatenate them.
SET ABS_PATH=%~dp0
SET REL_PATH=..\SomeFile.txt
SET COMBINED_PATH=%ABS_PATH%%REL_PATH%
it looks odd with \..\ in the middle of your path but it works. No need to do anything crazy :)
In your example, from Bar\test.bat, DIR /B /S ..\somefile.txt would return the full path.
PowerShell is pretty common these days so I use it often as a quick way to invoke C# since that has functions for pretty much everything:
#echo off
set pathToResolve=%~dp0\..\SomeFile.txt
for /f "delims=" %%a in ('powershell -Command "[System.IO.Path]::GetFullPath( '%projectDirMc%' )"') do #set resolvedPath=%%a
echo Resolved path: %resolvedPath%
It's a bit slow, but the functionality gained is hard to beat unless without resorting to an actual scripting language.
stijn's solution works with subfolders under C:\Program Files (86)\,
#echo off
set projectDirMc=test.txt
for /f "delims=" %%a in ('powershell -Command "[System.IO.Path]::GetFullPath( '%projectDirMc%' )"') do #set resolvedPath=%%a
echo full path: %resolvedPath%
Files See all other answers
Directories
With .. being your relative path, and assuming you are currently in D:\Projects\EditorProject:
cd .. & cd & cd EditorProject (the relative path)
returns absolute path e.g.
D:\Projects
SET CD=%~DP0
SET REL_PATH=%CD%..\..\build\
call :ABSOLUTE_PATH ABS_PATH %REL_PATH%
ECHO %REL_PATH%
ECHO %ABS_PATH%
pause
exit /b
:ABSOLUTE_PATH
SET %1=%~f2
exit /b