简体   繁体   中英

Windows Batch script copy the files modified in last x minutes

I am new in scripting. I want to copy the files modified in last x minutes in a batch script. In Linux there is a simple command to find and copy the .zip files modified in last x minutes.

find /user/log/ *.log  -mmin -180 -type f | cut -d '/' -f 5 | xargs tar -czvf /tmp/$name.tar.gz --directory=/user/log/

Is there any command available in windows which can be used to copy the files modified in last x minutes

as the .log file is constantly being modified by service logs Or how can I use forfiles command in terms of minutes or hours

This is relatively easy in PowerShell.

$ts = New-TimeSpan -Minutes 10
Get-ChildItem -File |
    Where-Object { $_.LastWriteTime -gt ((Get-Date) - $ts) }

To run this from cmd.exe you can either put the code above into a file with an extension of .ps1 and invoke it with PowerShell, or put it into the .bat script. There are many examples of doing this on SO and around the net.

Here is a more complete script that does copying as your question asked. Once you are satisfied that the correct files will be copied, remove the -WhatIf from the Copy-Item cmdlet.

$ts = New-TimeSpan -Minutes 180
Get-ChildItem -File -Filter '*.zip' |
    Where-Object { $_.LastWriteTime -gt ((Get-Date) - $ts) } |
    ForEach-Object {
        Copy-Item -Path $_ -Destination 'C:\new\dir' -WhatIf
    }

Note this is not an answer, it is added just as support to the accepted answer.

Here is an example of lit 's PowerShell code, (reduced a little using aliases) , ran directly from a batch script.

@Echo Off
Powershell -NoL -NoP -C "&{$ts=New-TimeSpan -M 180;"^
 "GCI "C:\MyDir\SubDir" -Fi '*.zip'|?{"^
 "$_.LastWriteTime -gt ((Get-Date)-$ts)}|"^
 %%{CpI $_.FullName 'D:\Backups\MyLogs' -WhatIf}}"
Pause

Just change the number of minutes, (currently 180 ) , on line 2 , the source, ( .zip files) , directory on line 3 and your destination directory on line 5 . If you're happy with the output, remove the -WhatIf from line 5 and remove line 6 .

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