如何在PowerShell中解析日期?

Mir*_*rek 7 powershell powershell-2.0

我编写了一个删除超过五天的备份的脚本.我通过目录的名称而不是实际日期来检查它.

如何将目录名称解析为日期以进行比较?

我的部分脚本:

...

foreach ($myDir in $myDirs)
{
  $dirName=[datetime]::Parse($myDir.Name)
  $dirName= '{0:dd-MM-yyyy}' -f $dirName
  if ($dirName -le "$myDate")
  {
        remove-item $myPath\$dirName -recurse
  }
}
...
Run Code Online (Sandbox Code Playgroud)

也许我做错了什么,因为它仍然没有删除上个月的目录.

整个脚本与Akim的建议如下:

Function RemoveOldBackup([string]$myPath)
{

  $myDirs = Get-ChildItem $myPath

  if (Test-Path $myPath)
  {
    foreach ($myDir in $myDirs)
    {
      #variable for directory date
      [datetime]$dirDate = New-Object DateTime

      #check that directory name could be parsed to DateTime
      if([datetime]::TryParse($myDir.Name, [ref]$dirDate))
      {
            #check that directory is 5 or more day old
            if (([DateTime]::Today - $dirDate).TotalDays -ge 5)
            {
                  remove-item $myPath\$myDir -recurse
            }
      }
    }
  }
  Else
  {
    Write-Host "Directory $myPath does not exist!"
  }
}

RemoveOldBackup("E:\test")
Run Code Online (Sandbox Code Playgroud)

例如,目录名称为09-07-2012,08-07-2012,......,30-06-2012和29-06-2012.

Aki*_*kim 12

尝试计算[DateTime]::Today解析目录名之间的差异和结果:

foreach ($myDir in $myDirs)
{
    # Variable for directory date
    [datetime]$dirDate = New-Object DateTime

    # Check that directory name could be parsed to DateTime
    if ([DateTime]::TryParseExact($myDir.Name, "dd-MM-yyyy",
                                  [System.Globalization.CultureInfo]::InvariantCulture,
                                  [System.Globalization.DateTimeStyles]::None,
                                  [ref]$dirDate))
    {
        # Check that directory is 5 or more day old
        if (([DateTime]::Today - $dirDate).TotalDays -ge 5)
        {
            remove-item $myPath\$dirName -recurse
        }
    }
}
Run Code Online (Sandbox Code Playgroud)