Bob V
Bob V

Reputation: 35

Powershell does not capture EXE exception when run as a scheduled task

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 <[email protected]>"
    $To = "[email protected]"
    $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.

Upvotes: 2

Views: 237

Answers (1)

Tanaka Saito
Tanaka Saito

Reputation: 1100

EDIT to clarify: The likely reason that it fails is that a program calling a program calling a program will not necessarily transfer permissions over. Even if the first call to CMD is running as administrator that doesn't mean the subsequent process will too. Removing as many nested calls as possible will reduce potential problems.

Original answer:

It looks like your scheduled task is running CMD that then calls the powershell script. You don't need to do that, you can run the powershell script directly in Task Scheduler.

Set the action in Task Scheduler to run the program C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe and in the 'Add Arguments' box you enter -File "C:\ScheduledJobs\MyScript.ps1" including double quotation marks. You may also need to change the execution policy by adding -ExecutionPolicy RemoteSigned depending on if the script is signed or not. If this is a demo/lab environment you could also use Bypass although that is not recommended in production environments.

I've had similar issues when trying to run CMD that then runs Powershell so just running the script as it is will probably solve your issue.

Upvotes: 1

Related Questions