Search directory name of a file. bat

Asked

Viewed 3,006 times

2

I have a. bat file that does some iterations via cmd in several directories. My problem is this:

  • I need to be able to get the directory of the file itself . bat to always be back to the same to make other iterations.

an example would be:

:exemplo
set file=C:\nome-do-diretorio\
for /f "tokens=*" %%A in (%file%) do ( cd %%A)

So far ok, but then I need the cmd can be pointed to the directory of the bat file itself.

  • In the powershell is (Get-Location).Path!

3 answers

4

You can use %cd%, this will return the current path where the batch is running.

Can test with echo %cd%

  • I’ve been doing some batch automations for some time and didn’t know about this variable. Thank you.

  • It’s Just this variable that I’m using and that’s where I discovered the problem. The %CD% variable takes the current directory where the cmd is pointed. I didn’t want to do a search on top of the file name, because it might take a while.

  • "but then I need the cmd to be able to be pointed to the directory of the bat file itself." I didn’t understand it got confused to me, you want the directory of the bat file?

2


Can use %~dp0

@echo off
echo "%~dp0"

1


inserir a descrição da imagem aqui


You can use variables and also their value/attribute/property expansions.

In the code below you have some variables that are fixed and you have others that are changed according to the actions of bat, as an example in directory exchanges.


@echo off & cd /d "%~dpn0"

for %%i in ("%windir%" "%appdata%" "%ALLUSERSPROFILE%")do cls & cd /d "%%~i" & call :^)
goto :eof

:^)
echo/ ----------------------------------------------------------------
echo/ variaveis nao alteram seus valores
echo/ ----------------------------------------------------------------
echo/ %%~d0              = %~d0
echo/ %%~p0              = %~p0 
echo/ %%~dp0             = %~dp0
echo/ %%~f0              = %~f0
echo/ %%~dpnx0           = %~dpnx0     
echo/ ----------------------------------------------------------------
echo/ pasta atual: %__CD__% 
echo/ ----------------------------------------------------------------
echo/ variaveis alteram seus valores para pasta atual
echo/ ----------------------------------------------------------------
echo/ %%CD%%              = %cd%
echo/ %%__CD__%%          = %CD%
echo/ ----------------------------------------------------------------
timeout -t 5 & exit /b 


Note: 1) More information about the variable expansions you have in the help co command for /?

Note: 2) You can set a variable to use when returning to the directory where the bat initially ran in this way:


set "_pasta_bat=%~dp0"

rem :: retornando para a pasta do bat :: 

cd /d "%_pasta_bat%"

rem :: ou apenas :: 

cd /d "=%~dp0"

Browser other questions tagged

You are not signed in. Login or sign up in order to post.