Forum Discussion
Powershell script via task scheduler not work as expected
If the same commands work fine from normal powershell console and if you face issue only in Task Scheduler, then the problem might be the user account that you have configured for the schedule task.
The command Send-MailMessage accepts the parameter -Credential. If you don't provide this parameter, then the command runs in the current user privilege. In your case, the account that you set in the schedule task ( Task -> Properties -> General tab -> Security Option -> When running the task, use the following account).
But I would recommend you to store your credentials in Windows Credentials Manager and retrieve it using PowerShell and use it in Send-MailMessage command.
Store Credentials
Install-Module -Name CredentialManager New-StoredCredential -Target "MyUserInfo" -UserName "username" -Password "mypwd"
Read the stored user credential from Windows Credentials manager
$psCred = Get-StoredCredential -Target "MyUserInfo"
You can change your script as shown in below command
Send-MailMessage -From "o365.service.eu@mydomain.com" -To stefan@mydomain.com -SmtpServer smtp.mydomain.com ` -Subject "Added picture for $mailAddress" -Credential $psCred
For this line : Start-Transcript -Path "transcript.txt" -Append (ne), provide complete path :
Start-Transcript -Path "C:\\LogFiles\transcript.txt"
Same for other paths:
$date2 = $date.ToShortDateString() + " - " + $date.ToShortTimeString()
$date2 + " - Uploaded picture for " + $mailaddress | "C:\\LogFiles\log.txt" -append
The strange thing with send-message is that if an error occurs, the send-message within the catch path works fine without using the -credential parameter.
For the Start-Transcript and out-file I use an UNC path (just shortened it in the provided code).
E.g.
Start-Transcript -Path "\\edc-derant202\EmployeePic\Scripts\transcript.txt" -Append
$date2 + " - Uploaded picture for " + $mailaddress | Out-File \\edc-derant202\EmployeePic\Scripts\log.txt -append
- Kevin_MorganSep 18, 2019Iron Contributor
Seems you have missed the parameter -Body in your inner query. Just provide some content for -Body parameter.
Send-MailMessage -From "o365.service.eu@mydomain.com" -To stefan@mydomain.com -SmtpServer smtp.mydomain.com ` -Subject "Added picture for $mailAddress" -Body "Added picture"
For the Start-Transcript, ensure that the schedule task account has valid permission (write) in the UNC path.
- machineslaveSep 18, 2019Copper Contributor
Thanks a lot.
Just added the -Body parameter and also verified / resolved the permissions of the UNC path.
Now it works properly.