【问题标题】:Powershell script is moving wrong files based on lastwritetimePowershell 脚本根据 lastwritetime 移动错误的文件
【发布时间】: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 的前四个字符是 12291220
  • 我说“没必要”,因为对于使用过其他基于文本的 shell 的 PowerShell 新手来说,这是一个常见的概念障碍。您可以直接使用DateTime 对象。

标签: powershell getdate get-childitem


【解决方案1】:
$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
}

【讨论】:

  • 好的,我明白了。我只需要在 lastwritetime 上使用日期,我不想要时间。有没有办法在不转换为字符串的情况下做到这一点?
  • 我知道你在找这个,我的第二个 sn-p 应该能满足你的需要。我将格式更改为可将日期排序为字符串 (yyyyMMdd)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-01
  • 1970-01-01
  • 2013-06-07
  • 1970-01-01
  • 2013-04-06
  • 1970-01-01
相关资源
最近更新 更多