我写了一个脚本,删除超过五天旧的备份。 我由目录的名称,而不是实际的日期进行检查。
如何解析目录名的日期进行比较呢?
我的脚本的一部分:
...
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
}
}
...
也许我做错事,因为它仍然不会删除上个月的目录。
与阿基姆的建议,整个脚本如下:
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")
目录名,例如,2012年9月7日,2012年8月7日,... 30-06-2012和29-06-2012。