batch filerecursion扫描一下存在,如果存在将其添加到zip总是失败

下面是一个接受2个或更多参数的batch file。 该

  1. 第一个参数应该是search文件的基本目录(例如D:\ temp)
  2. 第二个参数和连续的应该是要search的文件名模式(例如2017_02_01或myapp)

该batch file将执行以下操作

  1. 检查第一个参数是否为空并显示相应的消息。
  2. 检查第一个参数是否不存在目录或显示适当的消息。
  3. 调用一个子程序来parsing每一个参数并采取行动。
  4. 在子例程中检查是否有不需要的符号在参数中并显示相应的消息。
  5. 在子程序中不要对第一个参数采取行动。
  6. 在子例程中检查文件模式参数是否存在于作为第一个参数的基本目录中。 这里检查失败,总是返回1,这是不正确的。
  7. 如果文件模式参数存在,则采取像使用7zip将文件添加到临时zip文件的操作。 类似的做其余的参数。
  8. 如果参数为空,则停止子程序。

以下是batch file。

@echo off set BASE_DIR=%1 REM check if first argument is empty and display appropriate message set NEW_DIR=%BASE_DIR%X if %NEW_DIR%==X goto displayUsage REM check if first argument is not existing directory or display appropriate message if not exist %BASE_DIR% goto displayUsage cd /d C:\temp\ if exist "C:\temp\temp.zip" del /q /f "C:\temp\temp.zip" call :subr %* exit /b :subr rem check if any unwatned symbols are in arguments if exist "C:\temp\temp.txt" del /q /f "C:\temp\temp.txt" echo %* > "C:\temp\temp.txt" findstr /r ".*[<>/|?*%%].*" "C:\temp\temp.txt" >nul if %errorlevel% equ 0 goto displayUsage rem start parsing each argument for %%A in (%*) do ( if not %%A==%BASE_DIR% ( rem check if file exists and take action on it pushd %BASE_DIR% dir /b /s /ad *%%A* | find "File not found" set FILE_EXISTS=%errorlevel% rem HERE FILE_EXISTS STATUS IS ALWAYS 1 IRRESPECTIVE OF FILE PRESENCE popd if %FILE_EXISTS% equ 0 ( rem take action on the file like add it to a zip file "7za.exe" a -r -y "C:\temp\temp.zip" %BASE_DIR%\*%%A*.* ) else ( echo File %%A does not exists in %BASE_DIR% ) ) else ( echo No need to parse base directory %%A ) ) exit /b :displayUsage echo Usage: create-logs-zip.bat existing-base-directory log-file-name echo Do not use symbols: ^< ^> / ? ^| ^* goto end :end if exist "C:\temp\temp.zip" del /q /f "C:\temp\temp.zip" if exist "C:\temp\temp.txt" del /q /f "C:\temp\temp.txt" exit /b 

任何一点检查文件中的错误是否存在,并分享为什么总是返回1。

请求:请不要给power shell或cmdlet或VB脚本作为select。

延迟扩展是必要的,变量之间应使用感叹号而不是百分比。 以下是按预期工作的摘录

 for %%A in (%*) do ( if not %%A==%BASE_DIR% ( PushD "%BASE_DIR%" dir /b /s /ad *%%A* 2>null>&2 set FILE_EXISTS=!errorlevel! PopD if !FILE_EXISTS! equ 0 (%ZIPTOOL% a -r -y %TEMPZIP% %BASE_DIR%\*%%A*.*) else (echo File %%A is not found) ) else ( echo Skipping compressing of base-directory %%A ) )