如何解析在PowerShell中的日期?(How do I parse a date in Powe

2019-09-19 06:10发布

我写了一个脚本,删除超过五天旧的备份。 我由目录的名称,而不是实际的日期进行检查。

如何解析目录名的日期进行比较呢?

我的脚本的一部分:

...

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
  }
}
...

也许我做错事,因为它仍然不会删除上个月的目录。

与阿基姆的建议,整个脚本如下:

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")

目录名,例如,2012年9月7日,2012年8月7日,... 30-06-2012和29-06-2012。

Answer 1:

尝试计算之间的差别[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
        }
    }
}


文章来源: How do I parse a date in PowerShell?