Keeping PowerShell window open and Task Scheduler

7.8k Views Asked by At

I have a PowerShell script that I made a task for to run everyday. Is it possible to have the PowerShell window open (and not close after running) so I can make sure it runs without errors? When I schedule with the below command, no window pops up so I can't tell if it every really finished.

powershell -ExecutionPolicy ByPass -File “Q:\myscript.ps1” -NoExit

Additionally, within the script itself, I have a line that opens a text file in Notepad (the transcript of the script from Start-Transcript). When I run the script manually, it opens up Notepad, but the scheduled task did not. Is there a setting to get that to open?

$validationPath = "Q:\transcript.txt"
& Notepad $validationPath
1

There are 1 best solutions below

1
On BEST ANSWER

To run interactively you need to select Run only when user is logged on under security options. From the Task Security Context help:

You can specify that a task should run even if the account under which the task is scheduled to run is not logged on when the task is triggered. To do this, select the radio button labeled Run whether user is logged on or not . If this radio button is selected, tasks will not run interactively. To make a task run interactively, select the Run only when user is logged on radio button.

That said, if it is running as a scheduled task, in most cases it would be better to log the output and/or send a email on failure.

For logging you could use Start-Transcript, like this:

Start-Transcript -Path ('{0}\TaskName.{1:yyyy-MM-dd}.log' -f $env:temp, (Get-Date))
# Code here
Stop-Transcript

For email notifications you can use Send-MailMessage

try {
    # Code here
} catch {
    Send-MailMessage -To '[email protected]' -From '[email protected]' -Subject 'Error in script TaskName' -Body "Error $($_.Message) received while running TaskName" -SmtpServer smtp.domain.com
}