Powershell run job at startup with admin rights using ScheduledJob

后端 未结 3 841
一生所求
一生所求 2020-12-06 09:48

To ease some of my work I have created a powershell script which needs to :

  1. Run at startup.
  2. Run with admin rights as it has to write in c:\\program f
相关标签:
3条回答
  • 2020-12-06 10:08

    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."
        }
    }
    
    0 讨论(0)
  • 2020-12-06 10:16

    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.

    0 讨论(0)
  • 2020-12-06 10:27

    Please check the checkbox for "Run with highest privileges" for the task in the task scheduler and try again. Currently in the screenshot above it is unchecked.

    I have circled it below in red for your easy reference:

    0 讨论(0)
提交回复
热议问题