Author Posts

June 6, 2018 at 9:01 am

Param (
[string]$Path = "\\abcd\efgh\ijkl\mnop",
[string]$SMTPServer = "abcd.efgh.org",
[string]$From = "gkvdv@erb.org",
[string]$To = "bwerbp@erb.org",
[string]$Subject = "XXXXXX"
)
$file_attachments = @()

$SMTPMessage = @{
To = $To
From = $From
Subject = "$Subject at $Path"
Smtpserver = $SMTPServer
}

$File = Get-ChildItem $Path | Where { ($_.LastWriteTime -ge [datetime]::Now.Addminutes(-1440) ) -and ( $_.BaseName -like 'yyyy*') }
If ($File)
{ $SMTPBody = "`nThe following files have recently been added/changed:`n`n"
$File | ForEach { $SMTPBody += "$($_.FullName)`n" }
$File | ForEach {$file_attachments += $_.FullName}

Send-MailMessage @SMTPMessage -Body $SMTPBody -Attachments $file_attachments

}

The above code sends out an email when I run it in the powershell window.
But I schedule it in a task scheduler it runs successfully but not send out an email.

Under task scheduler tabs
Action:
Program/script : powershell
Add arguments ()optional‌:-ExecutionPolicy Bypass -file "\\abcd\efgh\ijkl\mnop\wgsgd.ps1"‌‌‌‌‌‌‌‌‌

Help is appreciated.
Thanks
‌‌‌‌

June 9, 2018 at 2:29 pm

Task Scheduler tends to run under LocalSystem. It's likely your mail server is rejecting the connection from the unauthenticated user.