我有一个powershell脚本,使用文件的lastwritetime将文件从一个文件夹移动到另一个文件夹。脚本正在检查lastwritetime是否小于或等于指定日期。似乎随着年份的变化,这已不再正常。我的文件的日期修改时间为2016年12月29日,2016年12月30日和2017年1月1日。 12/29文件应该是自今天是2017年1月3日以来移动的唯一文件,并且脚本使用该日期减去5天。因此,它应该只移动小于或等于12/29/2016的任何东西。但是,1/2 / 2017文件也被移动了。下面的脚本是关于为什么会发生这种情况的任何想法。
#Grab the day of the week it is TODAY
$DayofWeek = (Get-Date).DayofWeek
#Set the location we are going to be Pulling Files From
$FromPath = "path i'm copying files from goes here"
#Set the Location we are going to copy file To
$ToPath = "path i'm copying files to"
#Set a Default Value for DaysBack to Zero
$DaysBack = 0
#Set the Days Back if it is Tuesday through Friday
switch ($DayofWeek)
{
"Tuesday" { $DaysBack = -5 }
"Wednesday" { $DaysBack = -5 }
"Thursday" { $DaysBack = -3 }
"Friday" { $DaysBack = -3 }
"Saturday" { $DaysBack = -3 }
#If today is not an above day then tell the user today no files should be moved
default { Write-host "No files to move!" }
}
#if DaysBack does not equal ZERO then there are files that need to be moved!
if($DaysBack -ne 0) {
Get-ChildItem -Path $FromPath |
Where-Object { $_.LastWriteTime.ToString("MMddyyyy") -le (Get-Date).AddDays($DaysBack).ToString("MMddyyyy") } |
Move-Item -Destination $ToPath
}
答案 0 :(得分:0)
$date1 = Get-Date -Year 2017 -Month 1 -Day 2
$date2 = Get-Date -Year 2016 -Month 12 -Day 29
$date1 -gt $date2
#returns True
$date1.ToString("MMddyyyy") -gt $date2.ToString("MMddyyyy")
# "01022017" -gt "12292016"
# returns False
您可以使用
if($DaysBack -ne 0) {
Get-ChildItem -Path $FromPath |
Where-Object { $_.LastWriteTime -le (Get-Date).AddDays($DaysBack) } |
Move-Item -Destination $ToPath
}
或
if($DaysBack -ne 0) {
Get-ChildItem -Path $FromPath |
Where-Object { $_.LastWriteTime.ToString("yyyyMMdd") -le (Get-Date).AddDays($DaysBack).ToString("yyyyMMdd") } |
Move-Item -Destination $ToPath
}