@ECHO OFF
SETLOCAL
:: Starting directory
SET "sourcedir=U:\sourcedir"
:: name of directory to compress
SET "targetname=targetdir"
FOR /d /r "%sourcedir%" %%a IN (*) DO (
IF /i "%%~nxa" == "%targetname%" IF NOT EXIST "%%a\%targetname%\." (
ECHO compress %%a
rem temporarily switch to target directory
PUSHD "%%a"
ECHO 7z a -tzip "%%a.zip"
rem back to original directory
POPD
)
)
GOTO :EOF
This should do as you want - it will echo not execute the 7z
command.
The if
sees whether the "name and extension" portion of the directory-name in %%a
matches the target (the /i
makes the match case-insensitive). If it matches AND there is a subdirectory with the required name, then the compression portion is executed.
There are two points to consider.
First, the name of the destination ZIP file. As you have written it, the ZIP generated would be folder1.zip
in the parent directory. IDK what you want here. This code would do the same, but %%a.zip
could be replaced by ..\%targetname%.zip
since the pushd/popd
changes the current directory to the folder1
directory and ..
means the parent directory
.
The second matter is whether or not you want to compress ...\folder1\folder1
(which would have a destination ZIP file of ...\folder1\folder1.zip
)
Revision given comment:
@ECHO OFF
SETLOCAL
:: Starting directory
SET "sourcedir=U:\sourcedir"
:: name of directory to compress
SET "targetname=targetdir"
REM (
FOR /d /r "%sourcedir%" %%a IN (*) DO IF /i "%%~nxa" NEQ "%targetname%" (
rem calculate parent name in %%~nxp and grandparent in %%~nxg
FOR %%p IN ("%%~dpa.") DO FOR %%g IN ("%%~dpp.") DO (
IF /i "%%~nxp" == "%targetname%" IF /i "%%~nxg" NEQ "%targetname%" (
ECHO child %%~nxa
ECHO parent %%~nxp
ECHO Gparent %%~nxg Gppath=%%~dpg
ECHO compress %%a
rem temporarily switch to target directory
PUSHD "%%a"
ECHO 7z a -tzip "%%a.zip"
ECHO -------------------
rem back to original directory
POPD
)
)
)
GOTO :EOF
It's not that clear what you want to do with a directory named ...\folder1\folder1\something
or what the target ZIP file-name should be.
The if
in the for /d /r
line will ensure that only leaf-names that do not match the target name are processed. The path-name in %%a
is then processed into the parent and grandparent portions - note that %%~dp?
is the drive+path portion of %%?
which terminates \
so appending .
to this resolves to effectively removing the terminal \
yielding a "filename".
You appear to want to compress directories that have a parent but not a grandparent named with the target string, hence the innermost if
statement.
I've just echo
ed the various strings available at this point so they may be strung together as required to form your destination ZIP file-name. Note that the pushd/popd bracket ensures that the current directory at the time of the compress is the leaf to be compressed.