Remi Despres-Smyth
Remi Despres-Smyth

Reputation: 4253

UnauthorizedException trying to use Windows TaskScheduler wrapper

I have the following code, which uses version 2.5.20 of David Hall's TaskScheduler Nuget package, that wraps the Windows Task Scheduler. I'm trying to get all tasks from a specific folder, but for this question, let's just look at this code:

using (TaskService ts = new TaskService(_ServerName, _TaskSchedulerUsername, _DomainName, _TaskSchedulerPassword)) {
    var folder = ts.GetFolder(TASK_FOLDER_NAME);
}

The _TaskSchedulerUsername and _TaskSchedulerPassword is a valid local account with admin priviledges; I used these credentials to open the Windows Task Scheduler and manually create a task, as a test, and was able to do so without problems.

_ServerName and _DomainName are the same, the local machine.

This code used to work as-is, and is currently running without issue on my test server (which is running Windows server 2003); it also runs on a production Windows 2012 Server box. On my dev box (running Windows 10), I'm getting an UnauthorizedAccessException when I try to instantiate the new TaskService instance:

Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))

The stack trace isn't very helpful:

at Microsoft.Win32.TaskScheduler.V2Interop.TaskSchedulerClass.Connect(Object serverName, Object user, Object domain, Object password)
at Microsoft.Win32.TaskScheduler.TaskService.Connect()
at Microsoft.Win32.TaskScheduler.TaskService.EndInit()
at Microsoft.Win32.TaskScheduler.TaskService..ctor(String targetServer, String userName, String accountDomain, String password, Boolean forceV1)
at Test.TaskSchedulerServices.GetTaskSchedules() in C:\Projects\LE\dev\Test\Shared\Services\TaskSchedulerServices.svc.cs:line 54

Any ideas on why this won't run on my dev box, and what to do about it?

Upvotes: 3

Views: 2782

Answers (1)

Ben N
Ben N

Reputation: 2923

The Task Scheduler API changed significantly in Windows Vista. Your Server 2003 machine is on v1, while the new Windows 10 machine is on v2. In the case of v2, the NuGet package in question ends up calling ITaskScheduler::Connect. The documentation specifies that you can simply leave the server name null to connect to the local machine. (That should work for v1's SetTargetComputer as well.) The domain should be set to the computer's name if you're specifying a local user's name.

Though if you just want to connect to the local machine as the current user, you can just use the TaskService constructor that takes no parameters.

Upvotes: 1

Related Questions