触发时计划的 Powershell 不会运行,手动运行时不会停止运行

时间:2021-06-01 23:52:09

标签: powershell scheduled-tasks taskscheduler windows-task-scheduler

我正在尝试安排一个 Powershell 脚本从 Windows 任务调度程序运行。从 PS 窗口手动运行时,该脚本工作正常。但是,当我将其作为计划任务的操作时,会出现两个问题:

  1. 当触发发生时,任务不会启动。
  2. 当我从 Task Scheduler 中手动运行任务时,一个空的 Powershell 控制台窗口会出现几秒钟,然后消失。任务状态显示“正在运行”,并保持这种状态,直到我手动结束它。

我已确认已使用正确的用户权限设置任务。

我已在事件查看器中确认触发事件已发生并已正确记录。

任务的动作是:

<块引用>

“启动程序”程序/脚本:powershell 参数:-File "C:\Users\<username>\Desktop\script.ps1"

这是我的脚本的相关部分:

Start-Sleep -Seconds 2
If (!(Test-NetConnection -ComputerName www.example.com -InformationLevel "Quiet")) {
    #The code in here won't affect basic execution, since during testing this If condition evaluates to False
} Else { 
    [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
    [System.Windows.Forms.MessageBox]::Show("You're good to go!" , "Info" , 3)
    Exit
}

我希望当我测试这个任务时,我应该只是弹出消息框,然后任务应该停止运行。这些都没有发生,我真的不知道为什么。

1 个答案:

答案 0 :(得分:0)

问题是“在此系统上禁止运行脚本。”

<块引用>

about_Execution_Policies https://go.microsoft.com/fwlink/?LinkID=135170 安全错误:ParentContainsErrorRecordException |未经授权的访问

解决方案是将 -ExecutionPolicy Bypass 添加到任务参数中。 (现在屏幕上出现了一个单独的控制台窗口问题,-WindowStyle Hidden 没有解决,但是有很多关于该问题的类似文档,如果我找不到,我会发布一个新问题一个合适的解决方案)。