7z “Incorrect command line” when I run the script in a different drive than C:

元气小坏坏 提交于 2019-12-06 09:49:28

There are 2 mistakes in the batch code.

The first one is not making sure that path assigned to rootpath does not end with a backslash resulting in %%D containing a path with two successive backslashes.

Two successive backslashes in path caused by this coding omission mistake depends on parameter string on calling the batch or when the batch file is executed from root of a drive because in this case %cd% expands to a path consisting of drive letter, a colon and a backslash. %cd% expands to a path without a backslash at end if current directory is not root directory of a drive. However, this mistake is not critical.

The second one is the real problem on using a directory path containing a critical character like a space or one of these characters: &()[]{}^=;!'+,`~

%%D.7z and %%D\* are not enclosed in double quotes making the parameters list for 7za.exe invalid especially with 1 or more spaces in path.

How I found that out?

I inserted command echo left of 7za to see what would be executed in the loop. I don't have 7-Zip installed and therefore needed the echo to test the batch file.

The solution:

@echo off
if "%~1" == "" (
    set "RootPath=%CD%"
) else (
    set "RootPath=%~1"
)
if "%RootPath:~-1%" == "\" set "RootPath=%RootPath:~0,-1%"

for /D %%D in ("%RootPath%\*") do (
    7za.exe a -t7z "%%D.7z" "%%D\*" -mx9
)

If this batch file is executed on always the same computer where path to 7za.exe is known, it would be good to specify 7za.exe with full path enclosed in double quotes in the batch file.

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

  • cmd /? ... read at least the last paragraph on last output help page.
  • echo /?
  • for /?
  • if /?
  • set /?

Give a try for this batch file :

@echo off
set rootpath=c:\test
set strProgramFiles=%ProgramFiles%
if exist "%ProgramFiles(x86)%" set strProgramFiles=%ProgramFiles(x86)%
Set Path7z="%strProgramFiles%\7-zip\7z.exe"
echo %Path7z%
pause
CD /D "%rootpath%"
FOR /D %%D IN ("%rootpath%\*") DO (
  %Path7z% a -t7z %%D.7z %%D\* -mx9
)
pause
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!