我需要将所有不超过3天的文件从文件夹c:/ t /复制到文件夹c:/ t / 1,我该如何制作?

时间:2019-07-16 08:31:46

标签: powershell

如何根据日期将文件从一个文件夹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

2 个答案:

答案 0 :(得分: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".

答案 1 :(得分:0)

如果您要获取少于3天的文件列表,则只需获取子项并将其传递到Where-Object

$now = [DateTime]::Now
$files = Get-ChildItem -File *.* | ? {$now.Subtract($_.CreationTime).TotalDays -lt 3}

(注意:?Where-Object的别名)

$files现在包含少于3天的所有文件。

您现在可以通过将$files列表传递到ForEach-Object命令来复制文件:

$files | % {Copy-Item $_ -Destination c:\t\1}

(注意:%ForEach-Object的别名)

将所有内容汇总在一起:

$now = [DateTime]::Now
$files = Get-ChildItem -File c:\t\*.* | ? {$now.Subtract($_.CreationTime).TotalDays -lt 3}
$files | % {Copy-Item $_ -Destination c:\t\1}

或者您可以使用管道将其像这样组合起来:

$now = [DateTime]::Now
Get-ChildItem -File c:\t\*.* | ? {$now.Subtract($_.CreationTime).TotalDays -lt 3} | % {Copy-Item $_ -Destination c:\t\1}