Search code examples
windowspowershellbatch-filecmdscripting

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


Solution

  • 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
        }