简体   繁体   中英

Determine dynamic file name in Windows batch script?

We have a single file in a fixed directory that will have the name database-xxxzip where xxx is a version number that can change.

We want to create a batch script that will unzip this file - we can use 7zip to unzip the file from a batch script but we need to be able to pass the file name to 7zip - how can we determine the file name in a batch script given that the file name will not be constant?

The script needs to unzip an archive and then run an ant file which was in the archive:

"C:\Program Files\7-Zip\CommandLine\7za.exe" x %FILE%
ant -f %UNZIPPED_ARCHIVE_DIR%\db.xml 

use the fantastic for loop

from the command line

for /f "tokens=*" %f in ('dir database-?.?.?.?.zip /b') do 7za xxx %f

from the batch file

for /f "tokens=*" %%f in ('dir database-?.?.?.?.zip /b') do 7za xxx %%f

where xxx is the options passes to 7zip

Source: extract.bat :

@echo off
::: extract.bat - Extract all database-*.zip files in the given folder
::: usage: extract.bat [folder]
:::     folder - Search for files here (defaults to current folder)

set search=database-*.zip /b
if "%~1" neq "" set search=%1\%search%

for /f "tokens=*" %%f in ('dir %search%') do (
  7z x %%f %%~nf
  ant -f %%~nf\db.xml
)

If you really need to exclude database zips that don't follow the version folder format (eg if there's one called database-old.zip and that shouldn't be extracted) then you'll need to find a regex matcher for the command line in Windows - which is possible. That -or- if you keep your version numbers down to a single digit, then you can use the ? single character match.

You may also want to add some checking (before 7z... line) to make sure he folder doesn't already exist and do something if it does.

powershell Expand-Archive x.x.x.zip "where_you_want_to_unzip"

如果您需要使用 7zip 解压缩,那么我无法帮助您通过批处理文件解压缩我总是只使用它。

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