Hello Jerry Huo
Welcome to Microsoft Q&A Platform, thanks for posting your query here.
If the task is created successfully when you run the PowerShell script manually after logging into the VM, but not during VM setup using the Custom Script Extension, it's possible that the task is being created in the wrong context or at the wrong time during VM setup.
To troubleshoot this issue, you can try the following steps:
- Check the output of the Custom Script Extension to see if there are any errors or warnings related to the task creation.
Check the Task Scheduler to see if the task was created but disabled or not triggered correctly. You can open Task Scheduler by searching for "Task Scheduler" in the Start menu or by running the taskschd.msc
command.
Try running the PowerShell script with the -Verbose
parameter to get more detailed output. For example:
$command = 'del /S /Q C:\Users...\AppData\Local\Temp* && for /D %x in (C:\Users...\AppData\Local\Temp*) do @rd /S /Q "%x"'
$trigger = New-ScheduledTaskTrigger -Daily -At "00:00"
$action = New-ScheduledTaskAction -Execute 'cmd.exe' -Argument "/c $command"
$taskName = "CleanupTempFiles"
try {
Register-ScheduledTask -TaskName $taskName -Trigger $trigger -Action $action -RunLevel Highest -Verbose -ErrorAction Stop
Write-Host "Scheduled task '$taskName' created successfully."
} catch {
Write-Host "Failed to create scheduled task '$taskName'. Error: $_"
}
This script adds the -Verbose
parameter to the Register-ScheduledTask
cmdlet to get more detailed output about the task creation process.
- Try running the PowerShell script with a delay or a retry mechanism to ensure that the Task Scheduler service is running and ready to accept new tasks. For example:
$command = 'del /S /Q C:\Users...\AppData\Local\Temp* && for /D %x in (C:\Users...\AppData\Local\Temp*) do @rd /S /Q "%x"'
$trigger = New-ScheduledTaskTrigger -Daily -At "00:00"
$action = New-ScheduledTaskAction -Execute 'cmd.exe' -Argument "/c $command"
Hope this helps.