【发布时间】:2017-01-04 01:48:43
【问题描述】:
我有一个 powershell 脚本,它使用文件的 lastwritetime 将文件从一个文件夹移动到另一个文件夹。该脚本正在检查 lastwritetime 是否小于或等于指定日期。随着年份的变化,这似乎不再正常工作。我的文件修改日期为 2016 年 12 月 29 日、2016 年 12 月 30 日和 2017 年 1 月 2 日。 12/29 文件应该是唯一移动的文件,因为今天是 2017 年 1 月 3 日,脚本使用该日期减去 5 天。因此,它应该只移动小于或等于 2016 年 12 月 29 日的任何内容。但是,2017 年 1 月 2 日的文件也被移动了。脚本如下,关于为什么会发生这种情况的任何想法。
#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
}
【问题讨论】:
-
LastWriteTime属性是一个DateTime对象。无需转换为字符串(.toString())。 -
不仅没有必要,这就是破坏脚本的原因。它将日期比较更改为文本比较,并且您的 MMddyyyy 的前四个字符是
1229与1220。 -
我说“没必要”,因为对于使用过其他基于文本的 shell 的 PowerShell 新手来说,这是一个常见的概念障碍。您可以直接使用
DateTime对象。
标签: powershell getdate get-childitem