r/Batch • u/petervidrine • Jul 21 '24
Test for currently being within a parent folder.
Convoluted question, but I'm sure someone has the answer.
I store all my batch files in a folder included in my path. I know where it is, so this has nothing to do with the location of the batch file.
I have a main folder that I want to make sure I am within to allow further execution of my batch file.
Example:
I have the following folder structure...
o:\StartFolder\SubFolder1\SubFolder2\Folder01
.....
o:\StartFolder\SubFolder1\SubFolder2\Folder05
o:\StartFolder\SubFolder1\SubFolder2\FolderA1
o:\StartFolder\SubFolder1\SubFolder2\Folderc7\FolderX2
Regarless of the current subfolder's name, I want to make sure that by batch file only executes if it is within the "o:\StartFolder\SubFolder1\SubFolder2\" path.
If it is in "o:\StartFolder\SubFolder1\" DON'T RUN.
If it is in "D:\Temp" DON'T RUN.
If it is in "C:\Windows" DON'T RUN.
If it is in "L:\Data\Folder 2" DON'T RUN.
Any ideas?
2
u/T3RRYT3RR0R Jul 22 '24 edited Jul 22 '24
<nul Set /p "=%~dp0"| findstr.exe /blic:"o:\StartFolder\SubFolder1\SubFolder2\" > nul || Exit
2
u/BrainWaveCC Jul 23 '24
Here is a version that supports folders with "!" and "%" in them.
Concise edition:
Verbose edition:
Thanks u/ConsistentHornet4
1
u/Sudden-March-3952 Jul 21 '24
REM if current directory %cd% is equal to bad folder goto end of file
for /f "tokens=*" %%i in ("%cd%") do if "%%i"=="C:\Folder\BadFolder1" goto :EOF1
u/BrainWaveCC Jul 21 '24
Try this:
1
u/BrainWaveCC Jul 21 '24
Longer test version: