用于复制上个月文件的脚本

时间:2018-03-31 18:20:11

标签: windows batch-file robocopy

我正在尝试使用robocopy复制文件。我要复制的文件应该是上个月(不是一个月),即如果我在3月份(任何一天)运行脚本,那么它应该复制所有带有2月时间戳的文件。我正在使用以下脚本:

robocopy source/*.prev destination maxage:20180201 minage:20180228

如何在这里使用日期作为变量,所以我不必每个月手动更改一次?

4 个答案:

答案 0 :(得分:0)

您可以像这样计算的最后日期:date -d "-$(date +%d) days -0 month" +%Y-%m-%d

今天输出:2018-02-28

第一个日期是一个简单的固定开始日期:date -d "-$(date +%d) days -0 month" +%Y-%m-01

今天执行哪一次:2018-02-01

您的命令可能是:

robocopy source/*.prev destination \
maxage:$(date -d "-$(date +%d) days -0 month" +%Y%m01) \
minage:$(date -d "-$(date +%d) days -0 month" +%Y%m%d)

编辑:由于这是使用GNU日期语法,这可能不适用于@ghoti

所述的unix

答案 1 :(得分:0)

拥有GNU约会你可以这样做:

start=$(date -d "$(date +%Y-%m-1) -1 month" +%Y%m%d)
end=(date -d "$(date +%Y-%m-1) -1 day" +%Y%m%d)
robocopy source/*.prev destination maxage:${start} minage:${end}

参见linux - Using date command to get previous, current and next month 看看为什么我们需要-d。在一个月的31个月, -1个月会破坏。

答案 2 :(得分:0)

让我假设POSIX兼容date可用 那怎么样:

#!/bin/bash

days[1]=31; days[2]=28; days[3]=31; days[4]=30
days[5]=31; days[6]=30; days[7]=31; days[8]=31
days[9]=30; days[10]=31; days[11]=30; days[12]=31

# current year and month
year=$(date +%Y)
month=$(( $(date +%m) + 0 ))

# previous month
if [[ "$month" = "1" ]]; then
    year=$(( $year - 1 ))
    month="12"
else
    month=$(( $month - 1 ))
fi
days=${days[$month]}

# a leap year correction
if [[ "$month" = "2" ]]; then
    days=$(( $days + ($year % 400 == 0 || ($year % 100 != 0 && $year % 4 == 0)) ))
fi

maxage=$( printf "%04d%02d%02d" $year $month 1 )
minage=$( printf "%04d%02d%02d" $year $month $days )

答案 3 :(得分:0)

@echo off
    setlocal enableextensions disabledelayedexpansion

    rem Initialize variables to hold the previous month information
    set "yyyy=" 
    set "mm="
    set "dd="

    rem The robocopy in the for command will generate an error with the current date
    for /f "tokens=1,2 delims=/" %%a in ('
        robocopy "|" . /njh
    ') do if not defined yyyy (
        rem Calculate previous month from current date
        set /a "mm=(1%%b-90) %% 12 + 1", "yyyy=%%a - !(mm %% 12)" 
        rem Calculate the last day of the previous month
        set /a "dd=30+((mm+mm/8) %% 2)+(-2+!(yyyy%%4)-!(yyyy%%100)+!(yyyy%%400))*!(%%b-3)" 
        rem Increase month and day for proper padding
        set /a "dd+=100", "mm+=100"
    )

    rem Leave only the two right digits in month and day
    set "mm=%mm:~-2%"
    set "dd=%dd:~-2%"

    rem Do the copy operation, selecting files from first to last days in previous month
    robocopy "x:\source" "y:\target" *.prev /maxage:%yyyy%%mm%01 /minage:%yyyy%%mm%%dd%
相关问题