powershell - 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.
解决方案
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
推荐阅读
- javascript - Google Sheets App Script If Else Function
- reactjs - React:访问在 src 文件夹内的 public 文件夹中找到的图像
- html - json中的字符串间距,将通过JS脚本代码显示在HTML页面中
- python - cs50扫雷算法,在迭代过程中设置改变大小
- image-processing - 提高 SSIM、PSNR 等过滤器的 ffmpeg 精度
- javascript - 如何使用 navigation.navigate -react native 在深度嵌套的导航器中设置特定屏幕
- javascript - 在具有本地存储的两个样式表之间切换
- python - 窃取命令 Discord.Py
- numpy - 在不升级 tf 的情况下将 tensorflow 数据集转换为 numpy(1.15 版)
- python - 如果在后台执行脚本,如何在 Blender Python 上使用旋转运算符?