Powershell run job at startup with admin rights using ScheduledJob Powershell run job at startup with admin rights using ScheduledJob windows windows

Powershell run job at startup with admin rights using ScheduledJob


This is code that is already in production that I use. If it does not work for you, you must have something else going on with your system.

function Invoke-PrepareScheduledTask{    $taskName = "UCM_MSSQL"    $task = Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue    if ($task -ne $null)    {        Unregister-ScheduledTask -TaskName $taskName -Confirm:$false     }    # TODO: EDIT THIS STUFF AS NEEDED...    $action = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument '-File "C:\Invoke-MYSCRIPT.ps1"'    $trigger = New-ScheduledTaskTrigger -AtStartup -RandomDelay 00:00:30    $settings = New-ScheduledTaskSettingsSet -Compatibility Win8    $principal = New-ScheduledTaskPrincipal -UserId SYSTEM -LogonType ServiceAccount -RunLevel Highest    $definition = New-ScheduledTask -Action $action -Principal $principal -Trigger $trigger -Settings $settings -Description "Run $($taskName) at startup"    Register-ScheduledTask -TaskName $taskName -InputObject $definition    $task = Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue    # TODO: LOG AS NEEDED...    if ($task -ne $null)    {        Write-Output "Created scheduled task: '$($task.ToString())'."    }    else    {        Write-Output "Created scheduled task: FAILED."    }}


If it works, it's not a script problem. Assign it to the SYSTEM account or make a separate service account instead of the Gagan account shown. Make sure that service account has "Permission to run as batch job" in your local security policy.


If you want to get rid of that "on battery" crap, add

-DontStopIfGoingOnBatteries -AllowStartIfOnBatteries

to New-ScheduledTaskSettingsSet options.

So, in Kory Gill answer, $settings becomes:

$settings = New-ScheduledTaskSettingsSet -Compatibility Win8 -DontStopIfGoingOnBatteries -AllowStartIfOnBatteries

so task will be created to get rid of battery restrictions.

If you just want to modify an existing task, you can do it with:

Set-ScheduledTask -taskname "taskName" -settings $(New-ScheduledTaskSettingsSet -DontStopIfGoingOnBatteries -AllowStartIfOnBatteries)

or from cmd:

powershell -executionpolicy bypass Set-ScheduledTask -taskname "taskName" -settings $(New-ScheduledTaskSettingsSet -DontStopIfGoingOnBatteries -AllowStartIfOnBatteries)