I have a PowerShell script that connects to a list of servers, and queries that scheduled tasks. (Something similar to https://community.spiceworks.com/scripts/show_download/2094-get-scheduled-tasks-from-a-computer-remote-or-local) It used to work fine on a Windows 2008R2 server. However, on a new Windows Server 2012 R2 server, it is giving the below error. Strange thing it only happens when connecting to the local machine, no errors to remote servers. And it doesn't raise any errors when running under my account using administrative privileges.
This article says
Unfortunately, unlike the Get-ScheduledTask cmdlet using this COMObject requires an elevated PowerShell console with administrative credentials.
But the script used to work just fine on Windows Server 2008 R2 servers.
Is there anything that can be tweaked to make the script work on 2012 R2 servers?
Exception calling "Connect" with "1" argument(s): "Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))" At C:\scripts\CheckSchedulers\CheckSchedulers.ps1:20 char:10 + ($TaskScheduler = New-Object -ComObject Schedule.Service).Connect($curSe ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : ComMethodTargetInvocation
The error is raised by my code, using the code from spiceworks, it is reproducible.
You're creating a Schedule.Service
object, assign it to a variable, and then try to call a Connect()
method on the result of that assignment. I would not expect this to work on any Windows or PowerShell version, and if it did on Server 2008 R2 that's most likely just incidental.
You need the Schedule.Service
object in a variable (because you're going to need it for other operations as well), and you must call Connect()
on that object, so you need to do this in two steps:
$TaskScheduler = New-Object -ComObject 'Schedule.Service'
$TaskScheduler.Connect($servername) # connect to remote Task Scheduler
If you're connecting to different servers in a loop you can re-use the object and just Connect()
to the next server.
For connecting to the local Task Scheduler service just remove $servername
and call the method without argument:
$TaskScheduler.Connect() # connect to local Task Scheduler
User contributions licensed under CC BY-SA 3.0