我有一个 PowerShell 脚本,我将其设置为每天运行的任务。是否可以打开 PowerShell 窗口(而不是在运行后关闭)以便我可以确保它运行时没有错误?当我使用以下命令安排时,没有弹出窗口,所以我无法判断它是否真的完成了。
powershell -ExecutionPolicy ByPass -File “Q:\myscript.ps1” -NoExit
此外,在脚本本身中,我有一行可以在记事本中打开一个文本文件(来自 Start-Transcript 的脚本副本)。当我手动运行脚本时,它会打开记事本,但计划任务没有。是否有设置可以打开它?
$validationPath = "Q:\transcript.txt"
& Notepad $validationPath
最佳答案
要以交互方式运行,您需要在安全选项下选择仅在用户登录时运行。来自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.
也就是说,如果它作为计划任务运行,在大多数情况下最好记录输出和/或在失败时发送电子邮件。
对于日志记录,您可以使用 Start-Transcript
,如下所示:
Start-Transcript -Path ('{0}\TaskName.{1:yyyy-MM-dd}.log' -f $env:temp, (Get-Date))
# Code here
Stop-Transcript
对于电子邮件通知,您可以使用 Send-MailMessage
try {
# Code here
} catch {
Send-MailMessage -To 'errors@domain.com' -From 'alerting@domain.com' -Subject 'Error in script TaskName' -Body "Error $($_.Message) received while running TaskName" -SmtpServer smtp.domain.com
}
关于powershell - 保持 PowerShell 窗口打开和任务计划程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41497122/