简体   繁体   中英

How to create a ZIP file with WinRAR with name of ZIP file being name of current folder?

I'm trying to make a .bat file that will zip select files with a filename that automatically matches the current folder name and a custom extension.

For example, within directory C:\\thisIsAFolder\\

Winrar a -afzip %thisIsAFolder%.PicZip *.jpg *.png *.gif

I was trying to use %CD% , but it doesn't work, possible due to a terminator at the end?

This is a small part of a larger batch file, but it is the only part that doesn't work.

I am open to an alternative to using a batch file.

This batch code could be used for this task:

@echo off
if not "%CD:~-1%" == "\" (
    for /F %%I in ("%CD%") do set "FolderName=%%~nxI"
) else (
    set "FolderName=Drive%CD:~0,1%"
)
"%ProgramFiles%\WinRAR\WinRAR.exe" a -afzip -cfg- -ibck -m0 -y "%FolderName%.PicZip" *.jpg *.png *.gif
set FolderName=

Note: The path to WinRAR.exe can be different on your machine depending on installation of WinRAR .

The environment variable CD holds the path to current directory. This path does not end with a backslash, except the current directory is the root directory of a drive.

The IF condition compares last character of current directory path with a backslash. Is the last character NOT a backslash, the command FOR is used to get from entire directory path the string after last backslash which is the name of the current directory. Otherwise the current directory is a root directory of a drive and name for folder is defined as Drive with drive letter appended.

The ZIP file is created with compression method store because of switch -m0 as *.jpg, *.png and *.gif files contain already compressed data and therefore a re-compression does not make much sense.

For an explanation of the switches open in WinRAR from menu Help the Help topics . On tab Contents open list item Command line mode and subitem Switches . Open help page Alphabetic switches list and read about the switches.

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

  • echo /?
  • if /?
  • for /?
  • set /?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM