how to delete files older then x days and send only email notification, if files are deleted by script. Here is my script.. files are deleted by script, but email notification is not working. If I delete the if clauses (if(!$messageBody)) then email notification is working, but I am getting email when no files are deleted, too.
Get-ChildItem temp*.zip -Path "c:\tempfiles" |
Where-Object { -not $_.PSIsContainer -and $_.LastWriteTime -lt (Get-Date).AddDays(-0) }|
ForEach-Object {
$_ | Remove-Item -force
-join $([datetime]::Now) + " " + $_.Name| Out-File -FilePath "c:\tempfiles\logs\dellogs.txt" -Append
$OF = "`r`n"
$messageBody = $_.Name + $OF + $messageBody
}
$date = ( get-date )
if(!$messageBody){
$smtpServer = ""
$smtpFrom = ""
$smtpTo = ""
$server = ""
$messageSubject = "Subject $server - $date"
$body= "files"
$smtp = New-Object Net.Mail.SmtpClient($smtpServer)
$smtp.Send($smtpFrom,$smtpTo,$messagesubject,$messagebody)
$messageBody=" "
}
if(!$messageBody){ }block. Also,!$messageBodywill always beFalseif you enter theforeachbecause of the newline characters. If you want to collect the file names in a list, then just create a list and add the files. Or you can just read the files fromdellogs.txt. - AdminOfThings