首页 > 解决方案 > 计划的 Powershell 触发时不会运行,手动运行时不会停止运行

问题描述

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

  1. 当触发发生时,任务不会启动。
  2. 当我从任务计划程序中手动运行任务时,一个空的 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
}

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

标签: powershellscheduled-taskstaskschedulerwindows-task-scheduler

解决方案


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

about_Execution_Policies https://go.microsoft.com/fwlink/?LinkID=135170 SecurityError: ParentContainsErrorRecordException | 越权存取

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


推荐阅读