powershell - 如何在PowerShell中解析日期?

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

也许我做错了,因为它仍然无法删除上个月的目录。

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

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

最佳答案

尝试计算[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
        }
    }
}

关于powershell - 如何在PowerShell中解析日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11393366/

相关文章:

function - 访问函数执行后在函数内部创建的变量

loops - 修改未枚举的对象时出错

json - ConvertFrom-Json 是否尊重 -ErrorAction

powershell-2.0 - 如何为我的 cmdlet 编写 Powershell 帮助

powershell - 找不到与参数名称 'PipelineVariable' 匹配的参数

windows - Read-Host 总是以冒号结尾

powershell - 在 PowerShell 7 中 try catch 后访问变量时出错

powershell - 如何在同一目录中复制不同名称的文件夹?

exception - 如何捕获另一个 Powershell 脚本中抛出的异常?

powershell - 带有Jobs的Get-Counter返回不可用的数据