EMIE
EMIE

Reputation: 117

C# Console Application run in Powershell viaTask Scheduler

I'm trying to get my console application to run via powersheell/task scheduler.

If I open powershell and manually run .\startReport.ps1 it works. The console application doesn't open, just runs silently in the background.

However, when I go to create a task via task scheduler, it fails... telling me it completed successfully. But it didn't.

Any ideas?

  $r = Get-Date
  $fileName =  ".\Logs\" + $r.Date.Year + "-" + $r.Date.Month + "-"+ $r.Date.Day + ".txt"

  .\MyApp.exe > $fileName

Upvotes: 0

Views: 1496

Answers (2)

Harms
Harms

Reputation: 67

How is your task scheduler configured? One of the possibilities is:

  1. In actions, select "Start a program". And program is

%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe

  1. Then, in "Add arguments" you write something like

cd d:\folderWithTheScript; .\TheScript.ps1

Then you can use relative to "d:\folderWithTheScript" pathes

Upvotes: 0

Aman Sharma
Aman Sharma

Reputation: 1990

Here is how I was able to perform this in my environment with minor modifications. The code in my script is as below. Notice that I am using absolute paths instead of relative as PowerShell will launch with C:\Windows\System32 as default path and you may not have permission to create a Logs folder and a log file in there.

startReport.ps1 Script contents:

$r = Get-Date
$fileName =  "C:\Data\Logs\" + $r.Date.Year + "-" + $r.Date.Month + "-"+ $r.Date.Day + ".txt"

& C:\Data\MyApp.exe > $fileName

Notice above that I am using & notation to execute an exe. You can also replace this with any command as well if you are using &. What you are doing is also correct. I would just recommend using absolute path.

Then in the Task Scheduler I have the below command:

PowerShell.exe -File "C:\Data\startReport.ps1"

Again I am using the absolute path to refer the ps1 file. You can provide PowerShell.exe for the "Program/Script" and -File "C:\Data\startReport.ps1" for the "Add Argument" section in the Action tab of the task scheduler.

Other Considerations

  1. Within Task Scheduler try running with the highest privilege by clicking "Run with highest privileges" checkbox on the General tab of Create Task dialog. If you don't want that then ensure that Task scheduler has appropriate permissions to create a log file.
  2. Do ensure that Logs folder exists.

Upvotes: 2

Related Questions