How do I resolve scheduled task created using DSC can't be started manually?

214 Views Asked by At

I've tried setting up a scheduled task using DSC (Desired State Configuration) that starts at "creation time" and restarts if it's stopped within 5 minutes using the configuration below...

1. Create the DSC-configuration

Save it as tasks.ps1

Configuration Tasks {

    Import-DscResource -ModuleName ComputerManagementDsc -ModuleVersion 8.4.0

    Node 'localhost' {
        ScheduledTask 'MyTask' {
            TaskName = 'My Task'
            TaskPath = '\My Scheduled Tasks'
            ActionExecutable = '%ProgramFiles%\PowerShell\7\pwsh.exe'
            ActionArguments = '-ExecutionPolicy Bypass %ProgramData%\MyTasks\MyTask.ps1 -Param1 a -Param2 b'
            ActionWorkingPath = '%ProgramData%\MyTasks\'
            ScheduleType = 'Once'
            ExecutionTimeLimit = '00:00:00'
            MultipleInstances = 'IgnoreNew'
            RestartCount = 2
            RepeatInterval = '00:05:00'
            RepetitionDuration = 'Indefinitely'
            ExecuteAsCredential = $TaskCredential
            Ensure = 'Present'
        }
    }
    
}

2. Create an example script

mkdir $env:ProgramData\MyTasks

@'
[CmdletBinding()]
param (
  $Param1,
  $Param2
)

Sleep -Seconds 120

Get-Process
'@ | Out-File $env:ProgramData\MyTasks\MyTask.ps1 -Encoding utf8

3. Prepare the prerequisites

New-LocalUser `
  -Name TaskEngine `
  -Password (ConvertTo-SecureString 'mypassword!1' -AsPlainText -Force)

Configure the account with the ntrights Logon as batch job (should preferably be part of the DSC of course, but I'm leaving it out as to simplify the DSC example)

Logon as batch job

4. Create the MOF

Install-Module ComputerManagementDsc -RequiredVersion 8.4.0

$TaskCredential = New-Object System.Management.Automation.PsCredential(
  'TaskEngine', 
  (ConvertTo-SecureString 'mypassword!1' -AsPlainText -Force)
)


$ConfigurationStructure = @{
  AllNodes = @(
   @{
      NodeName = 'localhost'
      PSDscAllowPlainTextPassword = $true
    }
  )
}

. .\Tasks.ps1

tasks -ConfigurationData $ConfigurationStructure

5. Apply the MOF

Start-DscConfiguration -Path .\Tasks\ -Verbose -Wait

6. Inspect the result in Task Scheduler

The scheduled task is created an runs correctly but

  • It has the Last Run Result set to 0x800710e0 a while in, during the execution
    The operator or administrator has refused the request
    This can be replicated by setting up the task manually in Task Scheduler
  • It can't be started manually
    The user account does not have the permission to run this task
  • Exporting it when running crashes the MMC
    (this is probably normal behavior)

Edit: Changes in accordance with Doug's comment
Edit: Changed the question

0

There are 0 best solutions below