powershell - 我需要将所有不超过 3 天的文件从文件夹 c:/t/ 复制到文件夹 c:/t/1 我该怎么做?
问题描述
如何根据日期将文件从一个文件夹复制c:\t
到另一个文件夹c:\t\1
(将复制不超过三天的文件)?如何修改此代码以输入源文件夹?
ls -File | ?{
$_.CreationTime -ge $(Get-Date).AddDays(-3) -and
$_.LastWriteTime -ge $(Get-Date).AddDays(-3)
} | Copy-Item -destination C:\ps\1
解决方案
这使用了稍微不同的方法。由于人们经常将日期数学颠倒过来,因此进行比较days old
而不是直接比较日期对象。
$SourceDir = $env:TEMP
$DestDir = 'D:\Temp'
# this gives you the date with the time set to midnite
$Today = (Get-Date).Date
$MinDaysOld = 3
$FileList = Get-ChildItem -LiteralPath $SourceDir -File
foreach ($FL_Item in $FileList)
{
$DaysOld = ($Today - $FL_Item.CreationTime.Date).Days
if ($DaysOld -gt $MinDaysOld)
{
'the file below is {0} days old.' -f $DaysOld
# remove the "-WhatIf" when you are ready to do it for real
Copy-Item -LiteralPath $FL_Item.FullName -Destination $DestDir -WhatIf
''
}
}
截断输出...
the file below is 21 days old.
What if: Performing the operation "Copy File" on target "Item: C:\Temp\user2310119_append-csv-to-TXT-file.txt Desti
nation: D:\Temp\user2310119_append-csv-to-TXT-file.txt".
the file below is 49 days old.
What if: Performing the operation "Copy File" on target "Item: C:\Temp\vscode-inno-updater-1559095937.log Destinati
on: D:\Temp\vscode-inno-updater-1559095937.log".
[*...snip...*]
the file below is 34 days old.
What if: Performing the operation "Copy File" on target "Item: C:\Temp\vscode-inno-updater-1560382575.log Destinati
on: D:\Temp\vscode-inno-updater-1560382575.log".
the file below is 7 days old.
What if: Performing the operation "Copy File" on target "Item: C:\Temp\vscode-inno-updater-1562704735.log Destinati
on: D:\Temp\vscode-inno-updater-1562704735.log".
推荐阅读
- mysql - 如何连接到mysql容器?
- gwt - 为什么 LibGDX 音高不适用于 GWT?
- c++ - 当其他库仍在使用动态库中的指针时如何删除它
- python - 如何使用正则表达式从字符串中删除字符副本?
- asp.net-core-mvc - SignOut 不会重定向到站点主页
- plot - 使用gnuplot绘制二进制数据时是否可以设置X轴时间范围?
- reactjs - 为什么我无法访问 Docker 中的 React 应用程序?
- reactjs - 在反应中更改状态数组索引处的样式对象
- python - Python 项目欧拉 #21
- opc - 将 ClientName 设置为 OPC Server