我想做一个PowerShell脚本,删除某个文件夹中任何类型的文件,当他们是7天的时候。我遇到的问题是创建一个日志文件,其中包含脚本运行时删除或先前删除的所有文件的日期、时间和名称。
我想知道是否有一种方法可以修改本页上的答案:https://stackoverflow.com/questions/12326171/powershell-script-to-delete-sub-folders-and-files-if-creation-date-is-7-days-bu?lq=1
我想这样,而不是发送电子邮件与报告,它将创建一个日志文件的所有文件删除的名称,时间和日期在文件夹中,我存储的脚本(请注意,我希望它每次附加日志文件,而不是覆盖它)。我很抱歉,因为我不知道如何编码,所以我一直在努力做这件事自己很长一段时间了,我一直在问问题,但似乎仍然无法让它工作。所以,如果有人能修改这个脚本,我将非常感激!谢谢你!
这是我对脚本所做的(如果它有帮助的话),但它不起作用(我又不知道如何编码):
$report_items = @()
# set folder path
$dump_path = "C:FileDeleterAutoDeleteFilesInThisFolder"
# set min age of files
$max_days = "-7"
# get the current date
$curr_date = Get-Date
# determine how far back we go based on current date
$del_date = $curr_date.AddDays($max_days)
# get the sub directories
$sub_dirs = Get-ChildItem $dump_path | Where-Object {!$_.PSIsContainer }
$sub_dirs | % {
if (Get-ChildItem $_.FullName -Recurse | Where-Object { $_.LastWriteTime -gt $del_date } ) {
$report_items += New-Object -Type PSObject -Property @{
Time = Get-Date -f "hh:mm:ss"
Message = "Skipping " + $_.FullName + " because it contains items newer than " + $del_date
}
}
else {
Remove-Item $_.FullName -Recurse
$report_items += New-Object -Type PSObject -Property @{
Time = Get-Date -f "hh:mm:ss"
Message = "Deleting " + $_.FullName + " because it contains no items newer than " + $del_date
}
}
}
$report_items | out-file "C:FileDeleterPruningReport.txt"
应该这样做:
Get-ChildItem -Path "C:FileDeleterAutoDeleteFilesInThisFolder" -Filter *.torrent -Recurse | Where { $_.CreationTime -lt (Get-Date).AddDays(-7) } | %{Remove-Item -Force; if ($?) {"$(Get-Date -Format 'MM-dd-yy HH:mm:ss.ff') $_.Name" | Add-Content 'C:FileDeleterPruningReport.txt'}}
(if ($?)
块的原因是仅在文件删除成功时才写入日志条目—您不想假设它成功了。)
不那么简洁,但我是PowerShell中不要过度流水线的粉丝。
[String] $strBaseDir = "c:temp";
[String] $strFileFilter = "*.txt";
[Int] $intDayThreshold = 7;
[System.IO.FileSystemInfo] $objFile = $null;
[Int] $intLastWriteDays = 0;
[String] $strLogFileName = "d:datayourlogfile.log";
Get-ChildItem -LiteralPath $strBaseDir -Filter $strFileFilter -Recurse | Where-Object{ ! $_.PSIsContainer } |
Foreach-Object {
$objFile = $_;
$intLastWriteDays = [Math]::Round((New-TimeSpan -Start $objFile.LastWriteTime -End (Get-Date)).TotalDays);
if ( $intLastWriteDays -ge $intDayThreshold ) {
Write-Output -InputObject ( "{0:G} : Deleting file [{1}] with last write time of [{2:G}], which is [{3}] day(s) ago." -f (Get-Date), $objFile.FullName, $objFile.LastWriteTime, $intLastWriteDays ) | Add-Content -Path $strLogFileName -PassThru;
$objFile | Remove-Item -Force -ErrorAction silentlyContinue;
if ( ! $? ) {
Write-Output -InputObject "ERROR : Failed to remove file." | Add-Content -Path $strLogFileName -PassThru;
} #if
} else {
Write-Output -InputObject ( "{0:G} : Skipping file [{1}] with last write time of [{2:G}], which is [{3}] day(s) ago." -f (Get-Date), $objFile.FullName, $objFile.LastWriteTime, $intLastWriteDays ) | Add-Content -Path $strLogFileName -PassThru;
} #else-if
} #Foreach-Object