Search code examples
batch-filecmd7zip

How to exclude file extension when using 7zip cmd line batch


I have a .batch script in my Send to folder on Windows which I use to compress multiple files in the folder to a .zip. The problem I'm having is, it's including the extension in the archive file name.

I've search on google, read a lot of posts on stackexchange etc and none of the solutions posted seem to work for me.

@echo off
for %%A in (*.*) do call :doit "%%A"
goto end

:doit
if "%~x1"==".bat" goto :eof
if "%~x1"==".7z" goto :eof
if "%~x1"==".zip" goto :eof
if "%~x1"==".rar" goto :eof
"C:\Program Files\7-Zip\7z.exe" a -tzip %1.zip %1 -sdel
goto :eof

:end

Myfile.txt -> MyFile.txt.zip

I want to remove the .txt from file name if possible.


Solution

  • You can use %~n1 which uses the filename only of the first argument. Here is a possible solution:

    @echo off
    for %%A in (*.*) do (call:doit "%%A")
    goto end
    
    :doit
    if "%~x1" NEQ ".bat" (
        if "%~x1" NEQ ".7z" (
            if "%~x1" NEQ ".zip" (
                if "%~x1" NEQ ".rar" (
                    "C:\Program Files\7-Zip\7z.exe" a -tzip %~n1.zip %~n1 -sdel
    
    :end
    exit /b 0