首页 > 解决方案 > 连接到 localhost 时 Schedule.Service 出错

问题描述

我有一个连接到服务器列表并查询计划任务的 PowerShell 脚本。(类似于https://community.spiceworks.com/scripts/show_download/2094-get-scheduled-tasks-from-a-computer-remote-or-local)它曾经在 Windows 2008R2 服务器上运行良好。但是,在新的 Windows Server 2012 R2 服务器上,出现以下错误。奇怪的是它只在连接到本地机器时发生,远程服务器没有错误。并且在使用管理权限在我的帐户下运行时不会引发任何错误。

https://www.powershellmagazine.com/2015/04/10/pstip-retrieve-scheduled-tasks-using-schedule-service-comobject/

这篇文章说

不幸的是,与使用此 COMObject 的 Get-ScheduledTask cmdlet 不同,它需要具有管理凭据的提升的 PowerShell 控制台。

但该脚本过去在 Windows Server 2008 R2 服务器上运行良好。

有什么可以调整的以使脚本在 2012 R2 服务器上运行?

使用“1”参数调用“连接”的异常:“访问被拒绝。(异常
从 HRESULT: 0x80070005 (E_ACCESSDENIED))"
在 C:\scripts\CheckSchedulers\CheckSchedulers.ps1:20 char:10
+ ($TaskScheduler = New-Object -ComObject Schedule.Service).Connect($curSe ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ComMethodTargetInvocation

该错误是由我的代码引发的,使用来自 spiceworks 的代码,它是可重现的。

标签: powershellscheduled-tasks

解决方案


您正在创建一个Schedule.Service对象,将其分配给一个变量,然后尝试对该分配Connect()的结果调用一个方法。我不希望这适用于任何 Windows 或 PowerShell 版本,如果它适用于 Server 2008 R2,那很可能只是偶然的。

您需要Schedule.Service变量中的对象(因为其他操作也需要它),并且您必须调用Connect() 该对象,因此您需要分两步执行此操作:

$TaskScheduler = New-Object -ComObject 'Schedule.Service'
$TaskScheduler.Connect($servername)  # connect to remote Task Scheduler

如果您在循环中连接到不同的服务器,您可以重复使用该对象并仅Connect()连接到下一个服务器。

要连接到本地任务计划程序服务,只需删除$servername并调用不带参数的方法:

$TaskScheduler.Connect()  # connect to local Task Scheduler

推荐阅读