过去一年的日期比较为假

时间:2014-02-13 22:54:43

标签: windows powershell powershell-v2.0

我有一个通过目录递归的小脚本。应删除任何超过X天的文件。

这适用于当年,但它没有看到或从2013年删除文件。我在想$ _. LastWriteTime和(Get-Date).AddDays()之间的日期比较不知何故不是相同类型(或以这种方式出现)。

在我的源代码中,我打印文件名信息,而不是真正删除文件以进行测试。另外,当我运行时,我的实际文件结构如下所示:

Get-ChildItem -Path $myPath -Recurse -Force | % { Write-Host $_.FullName " - " $_.LastWriteTime }
  • \ MyNAS \ archive - 2/13/2014 1:01:33 PM
  • \ MyNAS \ inbound - 2/13/2014 12:49:32 PM
  • \ MyNAS \ outbound - 2/13/2014 12:45:14 PM
  • \ MyNAS \ temp - 2/13/2014 1:00:03 PM
  • \ MyNAS \ archive \ 13090318.res - 9/3/2013 11:46:28 AM
  • \ MyNAS \ inbound \ archive - 2/13/2014 12:49:32 PM
  • \ MyNAS \ inbound \ Error - 2/13/2014 1:01:07 PM
  • \ MyNAS \ inbound \ archive \ 14020445.exp - 2/4/2014 4:26:36 PM
  • \ MyNAS \ inbound \ archive \ 14020449.res - 2/4/2014 5:12:24 PM
  • \ MyNAS \ inbound \ archive \ 14021157.exp - 2/11/2014 4:41:30 PM
  • \ MyNAS \ inbound \ archive \ 14021157.res - 2/11/2014 4:41:31 PM
  • \ MyNAS \ inbound \ Error \ 13091117.tmp - 9/11/2013 7:09:00 AM
  • \ MyNAS \ inbound \ Error \ 14021036.tmp - 2/10/2014 2:18:10 PM
  • \ MyNAS \ inbound \ Error \ 14021137.tmp - 2/11/2014 1:24:21 PM
  • \ MyNAS \ outbound \ ARCHIVE - 2/13/2014 5:12:54 PM
  • \ MyNAS \ outbound \ ARCHIVE \ 13081402.tmp - 2013年8月14日 4:57:54 PM
  • \ MyNAS \ outbound \ ARCHIVE \ 14021056.csv - 2/10/2014 2:11:32 PM
  • \ MyNAS \ outbound \ ARCHIVE \ 14021157.csv - 2/11/2014 4:37:55 PM
  • \ MyNAS \ temp \ 13091935.exp.tmp - 9/19/2013 10:13:41 AM

代码:

param([String]$myPath="")
$limit = (Get-Date).AddDays(-33).ToShortDateString()

Write-Host "Looking in : $myPath"
Write-Host "Purging anything older than : $limit"

if ($myPath.length -gt 0) {
Get-ChildItem -Path $myPath -Recurse -Force | Where-Object { $_.LastWriteTime.ToShortDateString() -lt $limit } | % { Write-Host $_.FullName " - " $_.LastWriteTime.ToShortDateString() }
} else {
Write-Host "Source path not passed. Please pass the source path to purge"
}

1 个答案:

答案 0 :(得分:0)

我的问题安德鲁莫顿(谢谢!)指出我没有正确地投射我的变量。我不需要比较字符串,而是需要比较日期时间变量。这是固定的工作代码:

param([String]$myPath="")
$limit = [datetime](Get-Date).AddDays(-33)

Write-Host "Looking in : $myPath"
Write-Host "Purging anything older than : $limit"

if ($myPath.length -gt 0) {
Get-ChildItem -Path $myPath -Recurse -Force | Where-Object { [datetime]$_.LastWriteTime -lt $limit } | % { Write-Host $_.FullName " - " $_.LastWriteTime.ToShortDateString() }
} else {
Write-Host "Source path not passed. Please pass the source path to purge"
}