如何以编程方式设置任务计划程序安全选项?

How to programatically set Task Scheduler security options?

我正在尝试在 Windows 任务计划程序的安全选项部分设置 'Run whether user is logged on or not' 选项。

我正在使用 Task Scheduler Managed Wrapper

我试过这个:

using (TaskService taskService = new TaskService())
{
    try
    {
        TaskDefinition taskDefinition = taskService.NewTask();
        ...some triggers...
        taskDefinition.Actions.Add(new ExecAction( "iexplore.exe", vmsTask.Args, "C:\"));
        taskDefinition.Principal.LogonType = TaskLogonType.None;
        taskService.RootFolder.RegisterTaskDefinition("Task Name", taskDefinition);
    }
    catch (Exception e) 
    { }
}

这一行抛出异常:taskDefinition.Principal.LogonType = TaskLogonType.None;

例外情况是:

Value does not fall within the expected range.

实现此目标的正确方法是什么?

嗯,TaskLogonType.None 意味着

The logon method is not specified.

显然,这不是您想要的。您可能想要 PasswordServiceAccount("Run only when user is logged on" 是 ~InteractiveToken)。

我这样做了并且成功了:

using (var tasksrvc = GetTaskService(hostName, userName, password))
{
      tasksrvc.AddTask(
               taskName,
               QuickTriggerType.Daily,
               taskFolderPath,
               null,
               "UserName",
               "Password",
               TaskLogonType.Password);                    
}