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
Came across your post while trying to find a fix for my https://docs.microsoft.com/en-us/answers/questions/278958/script-runs-ok-manually-but-not-as-scheduled-task.html.
Standalone server, no domain, also trying to have my PS script Send-MailMessage using my M365 creds (app password). Works fine from powershell, but when trying to schedule the task the Get-StoredCredential command does not find my target "M365SMTPCred".
I have run the New-StoredCredential command as the local builtin Administrator. This is also the user running the task.
When I run Get-StoredCredential from task scheduler, I only get 2 stored credentials (and they are not my M365SMTPCred target), whereas I get 4 when running it direct from Powershell (and here I do see M365SMTPCred)
Any ideas why my local Administrator account cannot access my Get-StoredCredential -target "M365SMTPCred" from a scheduled task running as the same user?
Thanks in advance.