I want to create a schedule task using PowerShell which will create the task with a specified user and set the task to run weather the user is logged in or not and passes in the password.
This code will create the task but only set to run if the user is logged in.
# Define the trigger to start the task once at 7 AM, with a 10-minute repetition interval for a duration of 1 day
$trigger = New-ScheduledTaskTrigger -Once -At 7am -RepetitionDuration (New-TimeSpan -Days 1) -RepetitionInterval (New-TimeSpan -Minutes 10)
# Define the action to run PowerShell with the specified script and arguments
$action = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument '-file "XXXXXX.ps1"'
# Define the principal to run the task under a service account with the highest privileges
$user = New-ScheduledTaskPrincipal -UserID "XXXXXX" -LogonType ServiceAccount -RunLevel Highest
# Create the scheduled task with the defined trigger, action, and principal
$task = New-ScheduledTask -Action $action -Trigger $trigger -Principal $user
# Register the scheduled task under the specified path
Register-ScheduledTask -TaskName "XXXX" -InputObject $task
I have managed to get the task to run regardless of if the user is logged in or not but it just errors out
Run both as the service account and whether user is logged on or not # Define the trigger to start the task once at 7 AM, with a 10-minute repetition interval for a duration of 1 day
$trigger = New-ScheduledTaskTrigger -Once -At 7am -RepetitionDuration (New-TimeSpan -Days 1) -RepetitionInterval (New-TimeSpan -Minutes 10)
# Define the action to run PowerShell with the specified script and arguments
$action = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument '-file "XXXXXX"'
# Define the principal to run the task under a service account with the highest privileges
# Also set the task to run whether the user is logged on or not
$user = New-ScheduledTaskPrincipal -UserID "XXXXX" -LogonType S4U -RunLevel Highest
# Create the scheduled task with the defined trigger, action, and principal
$task = New-ScheduledTask -Action $action -Trigger $trigger -Principal $user
# Register the scheduled task under the specified path
Register-ScheduledTask -TaskName "XXXXX" -InputObject $task
The error message is “Register-ScheduledTask : Access is denied”