Powershell script can't execute Register-ScheduledJob as a Azure Resource Manager CustomScriptExtension

1.7k Views Asked by At

I have an deployment template for an azure virtual machine scale with this extensionProfile:

"extensionProfile": {
    "extensions": [
      {
        "name": "customScript",
        "location": "[resourceGroup().location]",
        "properties": {
          "publisher": "Microsoft.Compute",
          "type": "CustomScriptExtension",
          "settings": {
            "fileUris": [
              "[concat(parameters('customInstallScriptLocation'), parameters('customInstallScriptFileName'))]"
            ]
          },
          "typeHandlerVersion": "1.8",
          "autoUpgradeMinorVersion": true,
          "protectedSettings": {
            "commandToExecute": "[concat('powershell -ExecutionPolicy Unrestricted -File \"', parameters('customInstallScriptFileName'), '\" -adminUsername ', parameters('adminUsername'), ' -adminPassword ', parameters('adminPassword'))]"
          }
        }
      }
    ]
  }

When deploying the vmss the custom script is executed, commands like Invoke-WebRequest and Start-Process work without a problem. But Register-ScheduledJob doesn't work. When I connect to the remote desktop and run this install script manually everything works properly.

This is the code that fails when not running it manually:

$trigger = New-JobTrigger -AtStartup -RandomDelay 00:00:45
Register-ScheduledJob -Trigger $trigger -FilePath $installDir\natPuncherStartupScript.ps1 -Name NPSSOnStartup >> $log
logAndClearErrors $true

The error is:

Register-ScheduledJob : An error occurred while registering scheduled jobdefinition NPSSOnInstall to the Windows Task Scheduler.  The Task Scheduler error is: (32,4):UserId:.

I also tried:

$trigger = New-JobTrigger -AtStartup -RandomDelay 00:00:45
Register-ScheduledJob -Credential $credential -Trigger $trigger -FilePath $installDir\natPuncherStartupScript.ps1 -Name NPSSOnStartup >> $log
logAndClearErrors $true

But now an error shows that the username/password is invalid. Also when running this manually from remote desktop this works fine.

What am I missing? Why can't I schedule a job from a customscriptextension?

3

There are 3 best solutions below

2
On

According to your description, I could reproduce the errors you encountered by using Register-ScheduledJob.

From the official document about Register-ScheduledJob.

-Credential

Specifies a user account that has permission to run the scheduled job. The default is the current user.

I assumed that this issue is possibly casued by the user account that runs this scheduled job. After some trials, it could work as expected on my side and the scheduled job could be registered to my Azure VM by using ARM template. Here is the core command, you could refer to it.

$trigger = New-JobTrigger -AtStartup -RandomDelay 00:00:45
$pwd= ConvertTo-SecureString “{your-vm-adminPwd}” -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential (“{your-vm-adminName}”, $pwd)
Register-ScheduledJob -Trigger $trigger -FilePath $installDir\start1.ps1 -Name bruceScheduledJob -Credential $credential -Authentication CredSSP
0
On

You need to have it login as LocalSystem account if you want to have the vmextension register it.

Register-ScheduledTask -TaskName $jobname -Action $action -Trigger $trigger -RunLevel Highest -User "System" -Settings $settings

Stackoverflow link of this issue I had

1
On

I spent HOURS with the same problem and did not want to provide User/Password info in the script and other solutions failed. This PowerScript line finally worked (executes the batch command YourCommand):

&schtasks /create /tn YourTaskName /sc onstart /tr YourCommand /NP /DELAY 0001:00 /RU SYSTEM