Если я правильно понимаю вопрос, вы можете объединить это, используя массив housekeepingLog
путей и l oop над ними, что сэкономит вам много повторяющегося кода.
Основная проблема с ваш код заключается в том, что вы сразу же удаляете старые журналы, и поэтому после этого невозможно определить, что вы удалили ..
Примерно так:
# Declare file path to be housekeep
# first path in array is valid, second path is not
$housekeepLog = "D:\logs-Copy", "D:\logs-Copy2"
$timestamp = (Get-Date).ToString('yyyy-MM-dd HH:mm:ss')
foreach ($path in $housekeepLog) {
if (Test-Path $path -PathType Container) {
# the path exists, get logfiles older than 30 days
$refDate = (Get-Date).AddDays(-30).Date # set time to 00:00:00 (aka midnight)
# assuming the log files have the '.txt' extension.. If different, then change that in the Filter
$oldLogs = Get-ChildItem –Path $path -Filter '*.txt' -File -Recurse |
Where-Object {$_.LastWriteTime -lt $refDate}
if ($oldLogs) {
# save the full path and names of the old logfiles that are being deleted
$currentFolder = Split-Path -Path $path -Leaf
$outputFile = "D:\Housekeep-$currentFolder.txt"
Add-Content -Path $outputFile -Value $oldLogs.FullName
Add-Content -Path $outputFile -Value "$timestamp - Done housekeeping in $path.`r`n"
# remove the old log files
$oldLogs | Remove-Item -Confirm:$false
}
else {
Write-Host "No log files older than 30 days found in $path"
}
}
else {
Write-Warning "The folder '$path' does not exist.`r`nCheck the folder path!"
# the path is not found, send email
$emailProperties = @{
To = "myemail@mydomain.com"
CC = "myemail@mydomain.com"
Subject = "Folder '$path' does not exist"
SmtpServer = "smptserver@mydomain.com"
From = "noreply@mydomain.com"
Priority = "High"
Body = "The folder $path does not exist.<br>Check the folder path!"
BodyAsHtml = $true
}
Send-MailMessage @emailProperties
}
}