3

我想注册一个新任务。我的应用具有管理员权限:

<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />

我试图在互联网上找到一些东西,但是有很多例子告诉我我做得对。
这是我得到的一个例外:

捕获 COMException 帐户限制正在阻止此用户登录。例如:不允许使用空白密码、登录时间受到限制或已强制执行策略限制。(HRESULT 异常:0x8007052F)

我不知道为什么它对我不起作用...

这是我的方法:

private void CreateTask()
{
    using (var ts = new TaskService())
    {
        string computerName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;

        TaskDefinition td = ts.NewTask();
        td.RegistrationInfo.Date = DateTime.Now;
        td.RegistrationInfo.Author = computerName;
        td.RegistrationInfo.Description = "This task is awesome.";

        var trigger = new DailyTrigger(1)
        {
            Enabled = true,
            StartBoundary = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd") + "T05:00:00")
        };
        td.Triggers.Add(trigger);

        td.Principal.Id = "Author";
        td.Principal.UserId = computerName;
        td.Principal.LogonType = TaskLogonType.Password;
        td.Principal.RunLevel = TaskRunLevel.Highest;

        td.Settings.MultipleInstances = TaskInstancesPolicy.IgnoreNew;
        td.Settings.DisallowStartIfOnBatteries = true;
        td.Settings.StopIfGoingOnBatteries = true;
        td.Settings.AllowHardTerminate = true;
        td.Settings.StartWhenAvailable = false;
        td.Settings.RunOnlyIfNetworkAvailable = false;
        td.Settings.IdleSettings.StopOnIdleEnd = true;
        td.Settings.IdleSettings.RestartOnIdle = false;
        td.Settings.AllowDemandStart = true;
        td.Settings.Enabled = true;
        td.Settings.Hidden = false;
        td.Settings.RunOnlyIfIdle = false;
        td.Settings.WakeToRun = false;
        td.Settings.ExecutionTimeLimit = TimeSpan.FromHours(8);
        td.Settings.Priority = (ProcessPriorityClass) 7;

        td.Actions.Add(new ExecAction(Path.Combine(Config.MainDir, "Scripts", "starter.bat"),
                                      workingDirectory: Path.Combine(Config.MainDir, "Scripts")));

        ts.RootFolder.RegisterTaskDefinition("My Task", td);
    }
}
4

2 回答 2

4

要“运行用户是否登录”,不需要这些行:

td.Principal.LogonType = TaskLogonType.Password;
ts.RootFolder.RegisterTaskDefinition("My Task", td);

相反,使用这一行:

ts.RootFolder.RegisterTaskDefinition(taskName, td, TaskCreation.CreateOrUpdate, "someUserId", "somePassword", TaskLogonType.Password);

我在这里表示感谢:https ://taskscheduler.codeplex.com/discussions/268726

于 2015-02-19T22:07:26.173 回答
3

如果设置为Principal.LogonTypeTaskLogonType.Password则必须为其提供密码。所以你有2个选择:

  1. 删除td.Principal.LogonType =TaskLogonType.Password`
  2. 指定密码
于 2013-11-01T17:29:56.880 回答