How to parse a date in PowerShell?

I am writing a script that deletes backups for more than five days. I check it by directory name, not by actual date.

How to parse a directory name with 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 } } ... 

Perhaps I am doing something wrong because it still does not delete directories last month.

The whole script with Akim's suggestions is given 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") 

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

+4
source share
1 answer

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 - $dirName).TotalDays -ge 5) { remove-item $myPath\$dirName -recurse } } } 
+8
source

All Articles