使用相同的扩展批处理脚本查找多个文件

时间:2017-02-14 01:34:39

标签: batch-file

我正在编写这个批处理脚本,但是当它查看文件扩展名的所有文件是否存在时,它会继续执行,甚至是文件存在的其他文件。感谢您的帮助!

@echo off
if not exist C:\Users\%USERNAME%\Desktop\workBackup (
    ::creates new folder 'workBackup'
    mkdir C:\Users\%USERNAME%\Desktop\workBackup
)

set TIMESTAMP=%DATE:~4,2%%DATE:~7,2%%DATE:~10,4%

if not exist C:\Users\%USERNAME%\Desktop\workBackup\%TIMESTAMP% (
    ::creates new folder to put work into
    mkdir C:\Users\%USERNAME%\Desktop\workBackup\%TIMESTAMP%    
)

if not exist C:\Users\%USERNAME%\Desktop\workBackup\%TIMESTAMP%\logs (
    ::creates logs folder
    mkdir C:\Users\%USERNAME%\Desktop\workBackup\%TIMESTAMP%\logs
)

if exist C:\User\%USERNAME%\Documents\workspace\out\log\*.xlsx (
    ::moves all xlsx files to workBackup folder
    move "C:\User\%USERNAME%\Documents\workspace\out\log\"*.xlsx C:\Users\%USERNAME%\Desktop\workBackup\%TIMESTAMP%\
) else (
    ::exits if file no files are found
    echo "Files not found" 
    exit /b
)
if exist C:\User\%USERNAME%\Documents\workspace\out\log\*.xlsx (
    ::moves all log files to workBackup folder
    move "C:\Users\%USERNAME%\Documents\workspace\out\log\"*.log C:\Users\%USERNAME%\Desktop\workBackup\%TIMESTAMP%\logs
) else (
    ::exits if file no files are found
    echo "Files not found" 
    exit /b
)

1 个答案:

答案 0 :(得分:0)

有几件事需要提及

  • 日期格式是每用户设置,最好从wmic获取日期
  • 创建文件夹结构时,最深的一个将暗示另一个
  • 不测试,制作和抑制最终错误信息。
  • 通过创建vars来减少errorprone冗余
  • 在整个路径上放置双引号,而不仅仅是其中的一部分
@echo off
for /f %%A in ('wmic os get LocalDateTime^|findstr ^^[0-9]') do Set _DT=%%A
Set yy=%_DT:~0,4%&Set MM=%_DT:~4,2%&Set dd=%_DT:~6,2%

Set "WBu=C:\Users\%USERNAME%\Desktop\workBackup"
Set "WBuDT=%WBu%\%dd%%MM%%yy%"
:: or reverse day and month %MM%%dd%%yy%
Set "WSpOL=C:\Users\%USERNAME%\Documents\workspace\out\log"

mkdir "%WBuDT%\logs" 2>NUL

::moves all xlsx files to workBackup folder
move "%WSpOL%\*.xlsx" "%WBuDT%\" 2>NUL||(Echo "%WSpOL%\*.xlsx" not found&Exit /b)

::moves all log files to workBackup folder
move "%WSpOL%\*.log" "%WBuDT%\logs\" 2>NUL||(Echo "%WSpOL%\*.log" not found&Exit /b)