I write a batch script:
@echo off
set "zip=C:\Program Files\7-Zip\7z.exe"
for %%f in (%*) do (
if exist "%%~f\" (
"%zip%" a -tzip "%%~f.zip" "%%~f\*" -mx0
) else (
"%zip%" a -tzip "%%~f.zip" %%f -mx0
)
)
When the user selects multiple files/folders and drag them on to the script file, each file/folder dragged is packed into a zip file.
It works fine in most cases. However, if the files being dragged are located in a directory whose filename contains parentheses, such as "myfolder(large)", the script fails out.
Can anyone tell what causes this issue and how to solve it?
For this problem I see the following options:
Escaping the parenthesis by ^ using an interim variable:
@echo off
set "ZIP=C:\Program Files\7-Zip\7z.exe"
set "ARGS=%*"
set "ARGS=%ARGS:^=^^%"
set "ARGS=%ARGS:&=^&%"
set "ARGS=%ARGS:(=^(%"
set "ARGS=%ARGS:)=^)%"
for %%F in (%ARGS%) do (
dir /A "%%~fF" | > nul 2>&1 findstr "DIR" && (
"%ZIP%" a -tzip "%%~F.zip" "%%~F\*" -mx0
) || (
"%ZIP%" a -tzip "%%~F.zip" "%%~fF" -mx0
)
)
This method resolves the issue with parentheses ( and ) as well as & and ^, but it is not robust against all characters that have special meanings for batch scripts, like <, > and |.
Enabling and applying delayed expansion for the problematic string:
@echo off
set "ZIP=C:\Program Files\7-Zip\7z.exe"
set "ARGS=%*"
setlocal EnableDelayedExpansion
for %%F in (!ARGS!) do (
endlocal
dir /A "%%~fF" | > nul 2>&1 findstr "DIR" && (
"%ZIP%" a -tzip "%%~F.zip" "%%~F\*" -mx0
) || (
"%ZIP%" a -tzip "%%~F.zip" "%%~fF" -mx0
)
setlocal
)
endlocal
I prefer this method as it solves issues with all special characters. The toggling of delayed expansion inside of the loop (relying on the Windows default where it is disabled) is done to have it disabled during expansion of the %%F variable instances as otherwise problems arise in case the strings contain exclamation marks !. The problem here is that delayed expansion consumes ! encountered on the command line. A for variable like %%F is expanded to its value before delayed expansion is performed; so if the %%F value contains a ! it disappears - unless delayed expansion is disabled, where the ! has no particular meaning.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With