Search code examples
batch-file7zip

Batch 7zip, Zip file into archive without any folders


I am new to batch, and currently practicing to create automation script. I am stuck with this right now. I want the zip file to only contain tm_user.data, but my codes will archive it as Fame\tm_user.data. I would really appreciate if any of you could help me with this.

Variables

set default_folder_name=Main Folder
set tm_folder_name=TM Folder
set local_dir=C:\%default_folder_name%
set tm_dir=%local_dir%\%tm_folder_name%

Main body

set /p id="Enter ID: "
set d = "tm_user.data"

if exist "%tm_dir%\%id%\Fame\%d%" (
    "C:\Program Files\7-Zip\7z.exe" a -tzip "%tm_dir%\%id%\Fame\%id%_fame.zip" "%tm_dir%\%id%\Fame\%d%"
    echo Process completed...
    timeout 2
    start "launch folder" "%tm_dir%\%id%\Fame"
    exit
) else (
        echo Error: %d% not found, please try again later!!
        timeout 5
        exit
    )
)

Solution

  • A few best practices for batch files.

    1. Don't not put spaces on either side of the equals symbol in the SET command. Spaces before the equals symbol become part of the variable name and spaces after the equal symbol get assigned to the variable.
    2. Do not assign quotes to variables but do use them to surround the assignment to protect special characters and from assigning trailing spaces to the end of the variable.

    I have chosen to use the PUSHD and POPD commands. The PUSHD command sets the working directory and stores the previous directory on the stack. The POPD command returns back to the previous stored directory. Using this technique you do not have to specify the paths within the 7zip command.

    @echo off
    set "default_folder_name=Main Folder"
    set "tm_folder_name=TM Folder"
    set "local_dir=C:\%default_folder_name%"
    set "tm_dir=%local_dir%\%tm_folder_name%"
    
    set /p "id=Enter ID: "
    set "d=tm_user.data"
    
    if exist "%tm_dir%\%id%\Fame\%d%" (
        pushd "%tm_dir%\%id%\Fame"
        "C:\Program Files\7-Zip\7z.exe" a -tzip "%id%_fame.zip" "%d%"
        echo Process completed...
        timeout 2
        start .
        popd
        exit
    ) else (
        echo Error: %d% not found, please try again later!!
        timeout 5
        exit
    )