简体   繁体   中英

Create PowerShell script to send an email if files are older than 30 minutes

I need to run a script against automatically created and purged files in a directory.

I used the script from here: http://www.experts-exchange.com/Programming/Languages/Scripting/Powershell/Q_26895555.html

The problem with this script is it sends the email regardless of whether it finds any offending files or not.

Also it detects the old file and sends an email but when it's time to check again it doesn't report the file again.

I would like to run this as a scheduled task (which I know how to do) but I want it to only send the email if it finds offending files and I want it to report the offenders every time it checks.

Thanks for any help.

The single-line answer would look something like this:

Get-ChildItem -Path c:\test | Where-Object -FilterScript { ([DateTime]::Now - $_.LastWriteTime).TotalMinutes -ge 30; } | ForEach-Object -Begin { $FileList = @(); } -Process { $FileList += $_.Name; } -End { Send-MailMessage -Body $FileList ... ... ... ...; };

In the -End ScriptBlock of the ForEach-Object cmdlet, you can call the Send-MailMessage command, and pass in the $FileList variable, which gets built during the -Process ScriptBlock of the ForEach-Object . Overall, this is turning into a fairly lengthy single-line command though, so we can break it down to make it more understandable, and define a nice, prettier message body for the e-mail.

Here is a longer answer, that breaks it down into pieces:

$FileNameList = @();
$FileList = Get-ChildItem -Path c:\test;

foreach ($File in $FileList) {
   if (([DateTime]::UtcNow - $File.LastWriteTimeUtc).TotalMinutes -ge 30) {
        $FileNameList += $File.Name;
    }
}

$MessageBody = @"
The following files were older than 30 minutes:

{0}
"@ -f ($FileNameList -join "`n");

Send-MailMessage -Body $MessageBody ... ... ... ...;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM