Using FOR or FORFILES batch command to individuall

2020-05-07 07:52发布

问题:

I have a set of .iso files in different directories and sub-directories:

 <folder1>
    app1.iso
    app2.iso
    app3.iso
    <subfolder1>
        app1a.iso
        app2a.iso
    <subfolder2>
        app2b.iso
        app3b.iso
<folder2>
    app4.iso
    app5.iso
    <subfolder5>
        app20.iso

Using a batch file and having 7-zip pre-installed (with PATH environment variable configured), I want to be able to archive each .iso to it's own individual .7z archive file. I don't want to archive all .iso's in a current folder into one archive.

I attempted to create my own 7-zip command in conjunction with the FORFILES:

FORFILES /P . /M *.iso /S /C "cmd /c 7z a -t7z @path.7z -mx9 -mmt >> C:\test\7z-log.txt"

However, what this does is:

app1.iso.7z - contains: app1.iso, app2.iso, app3.iso
app2.iso.7z - contains: app1.iso.7z, app1.iso, app2.iso, app3.iso
app3.iso.7z - contains: app1.iso.7z, app2.iso.7z, app1.iso, app2.iso, app3.iso
app1a.iso.7z - contains: app1a.iso, app2a.iso
app2a.iso.7z - contains: app1a.iso.7z, app1a.iso, app2a.iso

...

What I want is (each in their relevant folder or sub-folder):

app1.iso.7z - contains: app1.iso
app2.iso.7z - contains: app2.iso
app3.iso.7z - contains: app3.iso
app1a.iso.7z - contains: app1a.iso
...

Can anyone help me on the batch command?

回答1:

@ECHO OFF
SETLOCAL
SET "sourcedir=U:\sourcedir"
FOR /f "delims=" %%a IN (
  'dir /s/b /a-d "%sourcedir%\*.iso" '
  ) DO (
  ECHO(7z a -t7z "%%~fa.7z" "%%~fa" -mx9 -mmt 
)
GOTO :EOF

You would need to change the setting of sourcedir to suit your circumstances.

The required 7z commands are merely ECHOed for testing purposes. After you've verified that the commands are correct, change ECHO(7z to 7z to actually archive the files.

Note that the redirection-to-log is missing. This is done to allow the proposed actions to be displayed to the screen.