首页 > 解决方案 > 我需要将所有不超过 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

标签: powershell

解决方案


这使用了稍微不同的方法。由于人们经常将日期数学颠倒过来,因此进行比较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".

推荐阅读