1

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

3
  • As an addition. Both scripts work as intended when ran separately without the scheduled task. I am trying to run this from the background RMM and trying to keep it as a singularly ran script from the backend. Commented Dec 7, 2023 at 17:16
  • Variable $LocalAdminName is not defined, so it looks like $principal = New-ScheduledTaskPrincipal -UserId "$compName\$LocalAdminName" -LogonType S4U triggers the error message about the userId Commented Dec 7, 2023 at 18:29
  • $LocalAdminName is defined in a configuration.txt file. My sincere apologies, I tried to keep the excerpt as to the point as possible without having 100s of line of script that I was not having an issue with. Although, going back through it with you comment, I did notice that the $LocalAdminName variable is NOT was the variable is called in the config.txt....facepalm. About to see if that corrects my issue Commented Dec 7, 2023 at 18:35

1 Answer 1

1
  • 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

# ...
Sign up to request clarification or add additional context in comments.

2 Comments

I'm glad to hear it, @CyGorithm; my pleasure. I'm actually a little baffled, because when I tried to recreate the issue, I had trouble both with prefixing the target username with the local computer name and, when bypassing that, with the Register-ScheduledTask call giving me an "access denied" error when targeting a user other than the caller. Is the behavior different in domain environments, or did you have to modify other parts of your code too?
I changed it to use System rather than an actual user account. And it worked without an issue

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.