简体   繁体   English

Windows Batch脚本复制最近x分钟内修改的文件

[英]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. 我想将最近x分钟内修改的文件复制到批处理脚本中。 In Linux there is a simple command to find and copy the .zip files modified in last x minutes. 在Linux中,有一个简单的命令来查找和复制最近x分钟内修改的.zip文件。

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 Windows中是否有任何命令可用于复制最近x分钟内修改的文件

as the .log file is constantly being modified by service logs Or how can I use forfiles command in terms of minutes or hours 由于.log文件经常被服务日志修改,或者如何在几分钟或几小时内使用forfiles命令

This is relatively easy in PowerShell. 在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. 要从cmd.exe运行此文件,您可以将上面的代码放入扩展.ps1的文件中,然后使用PowerShell进行调用,也可以将其放入.bat脚本中。 There are many examples of doing this on SO and around the net. 有许多在SO和网络上执行此操作的示例。

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. 一旦确定要复制正确的文件,请从Copy-Item cmdlet中删除-WhatIf

$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. 这是直接从批处理脚本运行的lit的PowerShell代码示例(使用别名进行了一些简化)

@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 . 只需更改第2行的分钟数(当前为180分钟 ,源.zip文件) ,第3行的目录和第5行的目标目录。 If you're happy with the output, remove the -WhatIf from line 5 and remove line 6 . 如果您对输出感到满意,请从第5行中删除-WhatIf并删除第6行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM