powershell - 连接到 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 服务器上,出现以下错误。奇怪的是它只在连接到本地机器时发生,远程服务器没有错误。并且在使用管理权限在我的帐户下运行时不会引发任何错误。
这篇文章说
不幸的是,与使用此 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 的代码,它是可重现的。
解决方案
您正在创建一个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
推荐阅读
- python - 使用位置索引分配给 dask 系列
- r - 在 ubuntu 上的 anaconda 环境(基础)中安装 RStudio 时出现问题
- jupyter-notebook - 我想在 jupyter notebook 的 RISE 中去掉这个块
- javascript - 如何管理单个反应元素的状态以实现悬停效果?
- php - 无法根据 MySQL 数据在 Google Chart 中创建基线
- python - 使用函数对象作为 numba njit 函数的参数
- c# - 如何减少此程序中使用的 C# 代码量?
- css - 在反应形式中,无法输入文本字段或单击或悬停在按钮上
- node.js - 如何以高质量更改谷歌服务帐户个人资料图片?
- express - 命令性地运行 oneOf 验证?