1

This batch works fine for creating multiple archives in a folder but adds the root folder to the archive. I would like it to only add the files inside the root. This is the code I have:

for /d %%X in (*) do "C:\Program Files\7-Zip\7z.exe" a "%%X.zip" "%%X"

1 Answer 1

1

You simply need to use just a for loop omitting the /d parameter and it will work just as you describe creating the zip archive file(s) and not contain its parent folder.

Commands

Note: This will add a zip archive file for each file in the directory with only that file in the zip.

for %%X in (*) do "C:\Program Files\7-Zip\7z.exe" a "%%~X.zip" "%%~X"

Note: This will add all files only in the directory to the one zip file you specify.

for %%X in (*) do "C:\Program Files\7-Zip\7z.exe" a "<MyZipFileName>.zip" "%%~X"

Nest Loop Command

Note: This will add files only from the directories beneath the directory which the batch file resides to a zip file matching the name of the directory.

@ECHO ON

FOR /F "TOKENS=*" %%A in ('DIR /S /B /AD "*"') DO (
  FOR %%B IN (*) DO (
      "C:\Program Files\7-Zip\7z.exe" a "%%~fA.zip" "%%~fA\*")
)
EXIT

Further Resources

  • For /F
  • FOR /?

        tokens=x,y,m-n  - specifies which tokens from each line are to
                          be passed to the for body for each iteration.
                          This will cause additional variable names to
                          be allocated.  The m-n form is a range,
                          specifying the mth through the nth tokens.  If
                          the last character in the tokens= string is an
                          asterisk, then an additional variable is
                          allocated and receives the remaining text on
                          the line after the last token parsed.
    
  • Dir
  • For
  • a (Add) command
2
  • Thanks, but it doesn't quite do what I need. The batch needs to zip multiple folders for example there is a main folder that contains the batch and all the folders that need to be separately zipped. My current code can zip all the files but for example, it zips each folder also so when I open zip I get foldername/contents where all I want when I open the zip is the contents. Sorry if my explanation is vague.
    – nead2ether
    Apr 10, 2018 at 9:25
  • @nead2ether Look over the new section I added labeled "Nest Loop Command" as well as the additional resource in the "Further Resources" section that from what I tested, does exactly what you need per your clarification. Apr 10, 2018 at 13:11

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .