Issues sending emails remotely using Powershell script – Server 2012 R2

Posted on

Problem :

We’re having issues when using the Invoke-Command command in Powershell to manually trigger a remote Scheduled Task on another system.

Here’s the situation: A server XXX has a scheduled task, that runs a Powershell script. Inside that script, at some point, it triggers this line of code: Invoke-Command -Computer "" -ScriptBlock {schtasks /run /tn "Windows Update - Email Reporting"}. The invoked scheduled task simply calls another Powershell script that gets content from an HTML file, and sends it by email.

The issue lies here: When the scheduled task is called via the Invoke-Command command, the task’s Powershell script runs, but no email is sent.
If I run the task manually, it works fine and the email is sent.
Both scheduled tasks are running as SYSTEM, if that matters.

The reason we’re doing it remotely like that is because we don’t want to allow multiple servers to send email internally, and want to restrict it to a single one.

Does someone know why that’s happening ?

Thanks in advance!

EDIT: Here’s the properly-formatted script:

    $Content = Get-Content "\slmtl-wsus01.XXX.incUpdate_Reports*.html"
$messageParameters = @{                         
                Subject = "Windows Update report - $((Get-Date).ToShortDateString())"                         
                Body = $Content | Out-String
                from = ""                   
                To = ""                     
                SmtpServer = ""                          
            Send-MailMessage @messageParameters -BodyAsHtml 

Solution :

You should wrap your command in a try/catch to log errors.

try {
    Send-MailMessage ..... -ErrorAction Stop
catch {
    AddContent $Error[0].Exception.Message -Path "C:Log.txt"

The ErrorAction Stop will allow you to catch any non-terminating errors.

I figured out the issue, while trying to figure it out using Cory’s method (which for some reason, yielded zero log file).

In my original script, after running Invoke-Command -Computer "" -ScriptBlock {schtasks /run /tn "Windows Update - Email Reporting"}, I had the following command: Move-Item "\slmtl-wsus01.XXX.incUpdate_Reports*.html" "\slmtl-wsus01.XXX.incUpdate_ReportsARCHIVE"
In my head, the Invoke-Command ..... command would wait for the actual remote-script to terminate, before moving on with the Move-Item script…but it didn’t. So while my main script was moving away the content of the folder, the remote-script was trying to get said-content, that didn’t exist anymore, therefore, sending no email.

Once again, my scripting abilities are only thwarted by my incomprehension, and a day has been wasted on this 😛

Leave a Reply

Your email address will not be published. Required fields are marked *