Powershell script via task scheduler not work as expected

New Contributor

Hi,

 

I have a script that connects to Office 365, reads a directory where .jpg files are stored (firstname.lastname@mydomain.com) and uploads each picture to the users profile.

Either if the upload succcessful or not, the script sends an email.

If I schedule this task via task scheduler, the script runs successful, but some commands are not executed.

Here's the script. I've appended (ne) after each line that is not being executed when running via task scheduler:

 

Start-Transcript -Path "transcript.txt" -Append (ne)
$password = get-content cred.txt | convertto-securestring
$credentials = new-object -typename System.Management.Automation.PSCredential -argumentlist "O365.Service.EU@mydomain.com",$password

$ExSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/?proxymethod=rps -Credential $credentials -Authentication Basic -AllowRedirection
Import-PSSession $ExSession -AllowClobber

$pictureList = Get-Item "OutlookPicture\*"
$ErrorActionPreference = "Stop"

foreach ($picture in $pictureList)
{
try
{
$name = $picture.Name.ToLower()
$len = $name.LastIndexOf(".jpg")
$mailAddress = $name.Substring(0,$len) + "@mydomain.com"
$mailbox = Get-Mailbox $mailAddress
Set-UserPhoto -Identity $mailAddress -PictureData ([System.IO.File]::ReadAllBytes($picture.VersionInfo.FileName)) -confirm:$false
Send-MailMessage -From "o365.service.eu@mydomain.com" -To stefan@mydomain.com -SmtpServer smtp.mydomain.com `
-Subject "Added picture for $mailAddress" (ne)
$date = Get-Date
$date2 = $date.ToShortDateString() + " - " + $date.ToShortTimeString()
$date2 + " - Uploaded picture for " + $mailaddress | log.txt -append (ne)
Remove-Item $picture.VersionInfo.FileName
}
catch
{
write-host "Error"
$error[0] | out-file error.log -append (ne)
Send-MailMessage -From "o365.service.eu@mydomain.com" -To stefan@mydomain.com -SmtpServer smtp.mydomain.com `
-Subject "Error on uploading profile picture" -Body $Error[0]
}
}

Stop-Transcript

 

Any idea?

Thanks

Stefan

 

 

5 Replies

@machineslave 

 

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

 

@Kevin Morgan 

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


@machineslave 

 

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.

@Kevin Morgan 

Thanks a lot.

Just added the -Body parameter and also verified / resolved the permissions of the UNC path.

Now it works properly.

@Kevin Morgan 

 

Came across your post while trying to find a fix for my own.

 

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.