Search code examples
powershellpowershell-2.0

Trying to create a scheduled task from a powershell script but continue to receive the error "register-scheduledtask : the parameter is incorrect


I am trying to create a scheduled task via a powershell script that will automatically execute a batch file when the local admin account logs in. For reference, I have the script updating the registry to automatically log the local admin in after the computer leaves the local domain and reboots.

function TestCo-createTask {
    Write-Output "" | Out-File -FilePath $outputFilePath -Append
    Write-Output "Creating a scheduled task to auto run the Azure Domain join Package" | Out-File -FilePath $outputFilePath -Append
    Write-Output "" | Out-File -FilePath $outputFilePath -Append

    # Copy the provisioning pkg and script to temp2
    $originalBatch = Join-Path $scriptDirectory "002AzureJoin.bat"
    $originalPPKGscript = Join-Path $scriptDirectory "azureJoinPPKG.ps1"
    $originalPPKG = Join-Path $scriptDirectory "Provisioning"
    Copy-Item -Path $originalBatch -Destination "C:\temp2" -Verbose | Out-File -FilePath $outputFilePath -Append
    Copy-Item -Path $originalPPKGscript -Destination "C:\temp2" -Verbose | Out-File -FilePath $outputFilePath -Append
    Copy-Item -Path $originalPPKG -Destination "C:\temp2" -Recurse -Verbose | Out-File -FilePath $outputFilePath -Append

    $PPKG = "C:\temp2\002AzureJoin.bat"
    $compName = $env:COMPUTERNAME

    $actionScript = {
        Start-Process -FilePath "cmd.exe" -ArgumentList "/c $using:PPKG" -Wait -Verb RunAs
    }

    $trigger = New-ScheduledTaskTrigger -AtLogOn
    $principal = New-ScheduledTaskPrincipal -UserId "$compName\$LocalAdminName" -LogonType S4U
    $setting = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -DontStopOnIdleEnd
    $action = New-ScheduledTaskAction -Execute $actionScript

    try {
        Register-ScheduledTask -TaskName "ETELBatchRunTask" -Action $action -Principal $principal -Trigger $trigger -Settings $setting -Force
        Write-Output "Task successfully registered." | Out-File -FilePath $outputFilePath -Append
    }
    catch {
        Write-Output "Error: $_" | Out-File -FilePath $outputFilePath -Append
    }
}

EXACT ERROR RECEIVED:

register-scheduledtask : the parameter is incorrect
(14.8): UserID:
At F:\PSScripts\TestEnv2\DomainBreak.ps1: 119 char: 9
Register-scheduledtask -taskname BatchRunTask -Action $action ...
categoryinfo: invalidargument: (PS_scheduledtask:root/Microsoft/...S_scheduledtask) [Register-scheduledtask], cimexception
fullyqualifiederrorid : HRESULT 0x80070057, register-scheduledtask

Any help is appreciated

I expect a scheduled task to be created and automatically run the batch file in an elevated state upon logon of the admin account.

UPDATE EDIT: I have gotten the task created. But when the task runs, it returns an error on the task scheduler that the "System cannot find the file specified"

The task scheduler action is set to: Action: start a program Details: Start-Process -FilePath "cmd.exe" -ArgumentList "/c $using:PPKG" -wait -Verb RunAs


Solution

    • You're using PowerShell's scheduled-task cmdlets (module ScheduledTasks) rather than the scheduled-job cmdlets from the - presumably obsolete, Windows PowerShell-only - PSScheduledJob module.

    • Scheduled tasks (which are system-wide features unrelated to PowerShell) require defining their actions as full process command lines, not just as pieces of PowerShell code in the form of script blocks { ... }).

    • While you could invoke PowerShell Code via the PowerShell CLI (powershell.exe for Windows PowerShell, pwsh for PowerShell (Core) 7+)) and its -Command parameter, there is no reason to do so here: you're trying to achieve elevation from the invoked PowerShell code (Start-Process -Verb RunAs), which cannot work from an invisibly running task, because there's no one respond to the UAC prompt. Instead:

      • Call New-ScheduledTaskPrincipal with -RunLevel Highest to ensure elevated execution of the task to begin with.

      • You can then invoke your batch file directly, as the argument to New-ScheduledTaskAction's -Execute parameter.

    Therefore:

    # ...
    
    # Request that the user run *with* elevation (-Runlevel Highest)
    $principal = New-ScheduledTaskPrincipal -RunLevel Highest -UserId "$compName\$LocalAdminName" -LogonType S4U
    # ...
    # Make the task run the batch file directly, which will now run elevated.
    $action = New-ScheduledTaskAction -Execute C:\temp2\002AzureJoin.bat
    
    # ...