I am executing a .Net program using a Powershell script. When I run the script in the ISE it captures exception messages in the $output variable. When I execute the same script as a scheduled task, $output is an empty array. The scheduled task command is:
cmd /c "powershell.exe -File C:\ScheduledJobs\MyScript.ps1" > job.log 2>&1
$ErrorActionPreference = 'Stop'
try
{
$output = C:\Utilities\SomeDotNetProgram.exe /s:"SOME_STORED_PROCEDURE" 2>&1
}
catch
{
Write-Host "+++", $output.Count, "---"
$From = "Database Administrator <xxx@xxx.com>"
$To = "xxx@xxx.com"
$Subject = "Scheduled task failed"
$Body = -join $output
if ($output.Count -eq 0)
{$body = "??"} #Only gets here when run as scheduled task
$SMTPServer = "mail.xxx.net"
$SMTPPort = "25"
Send-MailMessage -From $From -to $To -Subject $Subject -Body $Body -SmtpServer $SMTPServer -port $SMTPPort
}
How can I make this work in a scheduled task? This is running on Windows Server 2012 R2.