首页 > 解决方案 > Moving files older than X days not working in Powershell

问题描述

I have the following code:

$dt         = Get-Date -format "MM-dd-yyyy"
$logFolder  = '\\192.168.20.151\user_backups\Veeam_Logs'
$source     = "$logFolder\*.log"; $destination = "$logFolder\Backup Logs [$dt]"
New-Item -ItemType Directory -Path $destination -Force
Move-Item ($source | Where LastWriteTime -gt (Get-Date).AddDays(-7)) $destination -Force

I'm trying to move *.log files in its current directory (so not folders & not recursive) to its sub-folder but only those log files that are older than 7 days. For some reason the above isn't working as it's still copying files that are 20 days old. There's no error.

Also I don't want it to give me any errors if there are no *.log files to copy (or at least when there's no match). -ErrorAction SilentlyContinue didn't work for some reason.

Your help is appreciated.

标签: powershell

解决方案


To perform a condition against LastWriteTime attribute, you need to first return a FileInfoObject. A path string passed into Move-Item -Path won't have the attribute. You can do something like the following:

$dt         = Get-Date -format "MM-dd-yyyy"
$logFolder  = '\\192.168.20.151\user_backups\Veeam_Logs'
$destination = "$logFolder\Backup Logs [$dt]"
$source = Get-ChildItem -Path "$logFolder\*.log" | Where LastWriteTime -gt (Get-Date).AddDays(-7)
New-Item -ItemType Directory -Path $destination -Force
Move-Item -LiteralPath $source -Destination $destination -Force

$source here performs all the conditional logic. It is unclear if you want files newer or older than a certain date. If you want files that are newer than $date, you will want to use LastWriteTime -gt $date. If you want files older than $date, you will want to use LastWriteTime -lt $date.


You can have -Path value perform the logic, but you must pass in an expression.

$dt         = Get-Date -format "MM-dd-yyyy"
$logFolder  = '\\192.168.20.151\user_backups\Veeam_Logs'
$destination = "$logFolder\Backup Logs [$dt]"
$source = Get-ChildItem -Path "$logFolder\*.log"
New-Item -ItemType Directory -Path $destination -Force
Move-Item -LiteralPath ($source | Where LastWriteTime -gt (Get-Date).AddDays(-7)) -Destination $destination -Force

推荐阅读