Sebh1990
Sebh1990

Reputation: 23

get unknown filename to zip the file in batch

I am looking for a way to zip a file with an unknown filename. i am struggling on how to get the filename into my variable. this my code:

set HOST=%1
set DRIVELTR=%2
set OMGEVING=%3

FOR %%i IN (\\%HOST%\%DRIVELTR%$\%OMGEVING%\*.*) DO set filename="%%~i"

"C:\program files\7-zip\7z.exe" a -r -sdel  \\%HOST%\%DRIVELTR%$\%OMGEVING%\filename.zip \\%HOST%\%DRIVELTR%$\%OMGEVING%\filename.txt

Upvotes: 1

Views: 396

Answers (1)

MC ND
MC ND

Reputation: 70951

FOR %%i IN ("\\%~1\%~2$\%~3\*.*") DO (
    "C:\program files\7-zip\7z.exe" a -r -sdel  "%%~dpni.zip" "%%~fi"
)

Where

  • %~1 to %~3 are the arguments to the batch file without quotes

  • %%~dpni is the drive, path and name (without extension) of the file being referenced by %%i

  • %%~fi is the full path of the file being referenced by %%i

NOTE: As the .zip files are being generated in the same folder that is being iterated, it is possible that the for loop retrieves the new .zip files. If you can not narrow the wildcard or generate the .zip files elsewhere, you can check if the file extension is .zip before trying to compress the file

FOR %%i IN ("\\%~1\%~2$\%~3\*.*") DO if /i not "%%~xi"==".zip" (
    "C:\program files\7-zip\7z.exe" a -r -sdel  "%%~dpni.zip" "%%~fi"
)

Upvotes: 2

Related Questions