I need to make a condition for unzipping a file using batch.
The method is as follows: If dummy=1, the batch will unzip an xlsx file to a particular folder, else , it will copy another xlsx file directly to that folder.
my code is as follows:
set dummy=1
If %dummy% EQU 1 (
SET CHEMIN=C:\file_to_unzip
cd %CHEMIN%
for /f %%j in ('dir /b %CHEMIN%\*.zip') do (
C:\PROGRA~1\WinZip\Winzip32 -min -e -o -j %CHEMIN%\%%j %CHEMIN%
)
COPY "C:\file_to_unzip\*.xlsx" "C:\destination"
) else (
COPY "C:\file_to_copy\*.xlsx" "C:\destination"
)
The problem is that without the IF condition, the unzip command will work properly. But once the IF condition is included, the cmd will say that the zip file cannot be found. I am not sure what causes this issue and how to solve this.
Any help appreciated.
Do you have delayed expansion enabled? setlocal enabledelayedexpansion
With your example code above, the failure will occur due to the CHEMIN variable being set within the if statement. If a variable is set within a parentheses scope, the new value set for that variable will not be available until the all the sub scopes have ended. Run the following script to see what I mean:
@echo off
set "xValue=1"
echo.%xValue%
if 1 EQU 1 (
set "xValue=2"
echo.%xValue%
echo.!xValue!
)
If delayed expansion is disabled (which it is by default), the results will be
1
1
1
if enabled, add setlocal enabledelayedexpansion at the beginning
1
1
2
Try your script as follows. To use
setlocal enabledelayedexpansion
set dummy=1
If %dummy% EQU 1 (
SET CHEMIN=C:\file_to_unzip
cd !CHEMIN!
for /f %%j in ('dir /b !CHEMIN!\*.zip') do (
C:\PROGRA~1\WinZip\Winzip32 -min -e -o -j !CHEMIN!\%%j !CHEMIN!
)
COPY "C:\file_to_unzip\*.xlsx" "C:\destination"
) else (
COPY "C:\file_to_copy\*.xlsx" "C:\destination"
)
Another solution would be to just move the set CHEMIN=C:\file_to_unzip line outside of the if statement.
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