Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I parse a date in PowerShell?

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.

like image 895
Mirek Avatar asked Jul 09 '12 10:07

Mirek


People also ask

How do I parse a date in a string in PowerShell?

Use ParseExact to Convert String to DateTime in PowerShell The ParseExact method helps convert the specified date and time string to the DateTime data type. We have a variable $date , which contains the date in string format. You can check the data type using the GetType() method.

How do you parse a date?

parse() The Date. parse() method parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC or NaN if the string is unrecognized or, in some cases, contains illegal date values (e.g. 2015-02-31). Only the ISO 8601 format ( YYYY-MM-DDTHH:mm:ss.

How do you call a date in PowerShell?

The Get-Date cmdlet gets a DateTime object that represents the current date or a date that you specify. Get-Date can format the date and time in several . NET and UNIX formats. You can use Get-Date to generate a date or time character string, and then send the string to other cmdlets or programs.


1 Answers

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
        }
    }
}
like image 157
Akim Avatar answered Oct 05 '22 23:10

Akim