13

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. Commented 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 Commented 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 Commented 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. Commented Mar 4, 2016 at 8:11

1 Answer 1

26

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
        }
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

more or less it works for me but less means it doesn't remove last month dirs
Try to replace .Days with .TotalDays. See updated snippet
Now this snippet is culture invariant, could you try it?
A little late, but I think [DateTime]::Today - $dirName should be [DateTime]::Today - $dirDate.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.