powershell - 保持 PowerShell 窗口打开和任务计划程序

标签 powershell scheduled-tasks taskscheduler

我有一个 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/

相关文章:

powershell - Powershell-如何为Start-Job预先评估脚本 block 中的变量

powershell - TFS - 获取变更集范围

c# - 如何每 5 分钟调用一次 url

windows - 每天运行任务计划程序两次,但不是每小时运行一次

windows - 如何使用PowerShell将作者添加到Windows任务

generics - 电源外壳 。使用 'Add-Type'定义的类声明通用列表

powershell - 安装其他安装程序?

c# - 如何构建一个非常低分辨率的计时器?

scheduled-tasks - 运行计划任务执行批处理文件时保持命令行窗口打开

powershell - 任务计划的 Powershell 脚本不显示消息框