Powershell脚本正在根据lastwritetime移动错误的文件

Powershell脚本正在根据lastwritetime移动错误的文件,powershell,getdate,get-childitem,Powershell,Getdate,Get Childitem,我有一个powershell脚本,它使用文件的lastwritetime将文件从一个文件夹移动到另一个文件夹。脚本正在检查lastwritetime是否小于或等于指定日期。随着年份的变化,这似乎不再正常工作。我的文件修改日期为2016年12月29日、2016年12月30日和2017年1月2日。12/29文件应该是唯一移动的文件,因为今天是2017年1月3日,脚本使用该日期减去5天。因此,它应该只移动小于或等于2016年12月29日的任何内容。但是,2017年1月2日的文件也被移动了。下面是脚本,

我有一个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
}
你可以用

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 -le (Get-Date).AddDays($DaysBack) } |
    Move-Item -Destination $ToPath
}


LastWriteTime
属性是一个
DateTime
对象。不需要转换为字符串(
.toString()
)。不仅不需要,这也是破坏脚本的原因。它正在将日期比较更改为文本比较,并且MMddyyyy的前四个字符是
1229
vs
1220
。我说“无需”,因为这是PowerShell新手在使用其他基于文本的shell时遇到的常见概念障碍。您可以直接使用
DateTime
对象。
LastWriteTime
属性是
DateTime
对象。不需要转换为字符串(
.toString()
)。不仅不需要,这也是破坏脚本的原因。它正在将日期比较更改为文本比较,并且MMddyyyy的前四个字符是
1229
vs
1220
。我说“无需”,因为这是PowerShell新手在使用其他基于文本的shell时遇到的常见概念障碍。您可以直接使用
DateTime
对象。好的,我明白了。我只需要使用上一次写入的日期,但我不想要时间。有没有一种不转换成字符串的方法可以做到这一点?我知道你在寻找这个,我的第二个片段应该可以满足你的需要。我更改了格式,将日期作为字符串进行排序(
yyyyMMdd
)。好的,我明白了。我只需要使用上一次写入的日期,但我不想要时间。有没有一种不转换成字符串的方法可以做到这一点?我知道你在寻找这个,我的第二个片段应该可以满足你的需要。我更改了格式,将日期作为字符串进行排序(
yyyyMMdd
)。
if($DaysBack -ne 0) {
    Get-ChildItem -Path $FromPath |
    Where-Object { $_.LastWriteTime.ToString("yyyyMMdd") -le (Get-Date).AddDays($DaysBack).ToString("yyyyMMdd") } |
    Move-Item -Destination $ToPath
}