简体   繁体   中英

How to rename or create a zip file with the name of its content using a batch file

I have a batch and a vbs file to zip a folder with a specific directory name and copy it to another folder.

Does anyone have a clue how to zip a folder with the name of its content (filename) expanding the existing script I have?

With the following two scripts I can make the directories to be zipped and copied to another folder.

bat:

CScript zip.vbs C:\TEMP\zip\source\JEAR_20190115 C:\TEMP\zip\target\JEAR.zip

vbs:

'Get command-line arguments.
Set objArgs = WScript.Arguments
InputFolder = objArgs(0)
ZipFile = objArgs(1)

'Create empty ZIP file.
CreateObject("Scripting.FileSystemObject").CreateTextFile(ZipFile, 
True).Write "PK" & Chr(5) & Chr(6) & String(18, vbNullChar)

Set objShell = CreateObject("Shell.Application")

Set source = objShell.NameSpace(InputFolder).Items

objShell.NameSpace(ZipFile).CopyHere(source)

'Required!
wScript.Sleep 2000

Running the batch file which calls the vbs the folder's content (3 files) are zipped and copied to the target directory described in the bat file (C:\\TEMP\\zip\\target\\JEAR.zip).

The output filename is specified in the bat file but the goal is to have the filename of the zipped folder's content (filename). Which is JEAR_20180116.*

If I got your question correctly, I think you want to just take the string, split off the last directory name and then use that as a variable in setting your zip file:

@echo off
set "mypath=C:\TEMP\zip\source\JEAR_20190115"
if "%mypath:~-1%"=="\" set "mypath=%mypath:~0,-1%"
for %%i in (%mypath%) do set "last=%%~nxi"
CScript zip.vbs %mypath% C:\TEMP\zip\target\%last%.zip

Please take note, if you change your path to have a trailing backslash on your path ie:

C:\TEMP\zip\source\JEAR_20190115\

You would want to first get rid of that, but we could simply test for it with:

if "%mypath:~-1%"=="\" set "mypath=%mypath:~0,-1%"

So then the full script will be:

@echo off
set "mypath=C:\TEMP\zip\source\JEAR_20190115"
if "%mypath:~-1%"=="\" set "mypath=%mypath:~0,-1%"
for %%i in (%mypath%) do set "last=%%~nxi"
CScript zip.vbs %mypath% C:\TEMP\zip\target\%last%.zip

if however the if you want to name it to a file within the directory, you would need to be sure the filenames inside the folder are all the same, as we will only be able to set it using one name, which will be the last file in the list, we could check each name, but I assume you haev files with the same name, but different extensions:

@echo off
set "mypath=C:\TEMP\zip\source\JEAR_20190115"
for /f %%i in ('dir /b /a-d "%mypath%"') do set "last=%%~ni"
CScript zip.vbs %mypath% C:\TEMP\zip\target\%last%.zip

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