11

I write a script that removes backups older than five days. I check it by the name of the directory and not the actual date.

How do parse the directory name to a date to compare them?

Part of my script:

...

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

Maybe I do something wrong, because it still does not remove last month's directories.

The whole script with Akim's suggestions is below:

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

Directories names are, for example, 09-07-2012, 08-07-2012, ..., 30-06-2012, and 29-06-2012.

4
  • 1
    Could you try folowing steps in powershell console: 1. [DateTime] $a = New-Object DateTime; [DateTime]::TryParse("29-06-2012", [ref]$a); $a; ([DateTime]::Today - $a) -ge 5; 2. [DateTime]::TryParseExact("29-06-2012", "dd-MM-yyyy", [System.Globalization.CultureInfo]::InvariantCulture, [System.Globalization.DateTimeStyles]::None, [ref]$a); $a; 3. [DateTime]::TryParseExact("29-06-2012", "dd-MM-yyyy", [System.Globalization.CultureInfo]::InvariantCulture, [System.Globalization.DateTimeStyles]::None, [ref]$a); ([DateTime]::Today - $a) -ge 5. All sould be without errors.
    – Akim
    Jul 9, 2012 at 13:18
  • results in polish: 1) False 1 stycznia 0001 00:00:00 True, 2) True 29 czerwca 2012 00:00:00, 3) True True
    – Mirek
    Jul 9, 2012 at 13:32
  • Ok @Mirek, you have a culture at your sever that does not understand your dates correctly. it simple thinks that "01-02-2012" is 1st of February, but not 2nd of January. I'm going to update snippet in my answer
    – Akim
    Jul 9, 2012 at 13:37
  • As a side note, if you ever want to sort your directories/files by name, use yyyy-MM-dd naming scheme.
    – MKesper
    Mar 4, 2016 at 8:11

1 Answer 1

24

Try to calculate the difference between [DateTime]::Today and the result of parsing the directory name:

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
        }
    }
}
4
  • more or less it works for me but less means it doesn't remove last month dirs
    – Mirek
    Jul 9, 2012 at 12:22
  • Try to replace .Days with .TotalDays. See updated snippet
    – Akim
    Jul 9, 2012 at 12:35
  • Now this snippet is culture invariant, could you try it?
    – Akim
    Jul 9, 2012 at 13:40
  • A little late, but I think [DateTime]::Today - $dirName should be [DateTime]::Today - $dirDate. Jul 4, 2018 at 1:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.