Consider me as a PowerShell beginner. I’ve just started on it since last 3 months.
I’m struggling with writing a script where I need email notification if a specific folder does not change its archive bits in last 15min.
I’m using Get-ChildItem for this with multiple conditions. But I fail to achieve that. Can you guide me what are the condition & parameters I need to use?
I’m trying to combine Send-MailMessage and Get-ChildItem requirement. So far Send-MailMessage is not disturbing me. But the real challenge is for me is to compare and trigger the mail.
When I create scripts I usually build them in pieces. Even writing something simple like this, I test Get-ChildItem first and ensure it returns the files I expect. Then I test sending an email and finally I put all the pieces together and test more. The example places the file information in the body of the email. If you want to make it more appealing, you can use CSS to style the table. There is a free eBook above “Creating HTML Reports in PowerShell” that explains how to use HTML to do basic reporting. Take a look at the following code:
#Set the date 15 minutes in the past
$date = (Get-Date).AddMinutes(-15)
#Find files that are greater than 15 minutes ago
$files = Get-ChildItem -Path C:\Users\Rob\Desktop -Attributes archive |
Where-Object {$_.LastWriteTime -gt $date }
#If $files is not null
if ($files) {
#Create an HTML table with the file information
$htmlBody = $files | ConvertTo-HTML -Property Name, LastWriteTime -Title ("Found {0} files" -f $files.count)
#Splat mail parameters
$mailParams = @{
To = "abc@xyz.com"
From = "lab@xyz.com"
Subject = "Test-Mail"
SmtpServer = "smtp.abc.com"
Body = $htmlBody
BodyAsHtml = $true
}
Send-MailMessage @mailParams
}
else {
"No files found created after {0}" -f $date
}
Also, please use the code tags. Instructions are noted above the code posting.