22

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 files folder.

I created the startup service using powershell like this :

function MakeStartupService
{
    Write-Host "Adding script as a startup service"
    $trigger = New-JobTrigger -AtStartup -RandomDelay 00:00:15
    Try
    {
      Register-ScheduledJob -Trigger $trigger -FilePath "absolute_path" -Name "Job-name" -EA Stop
    }
    Catch [system.exception]
    {
        Write-Host "Looks like an existing startup service exists for the same. Overwriting existing job"
        Unregister-ScheduledJob "Job-name"
        Register-ScheduledJob -Trigger $trigger -FilePath "absolute_path" -Name "Job-name"
    }
}

The job is registered as a startup service successfully and is visible inside task scheduler. If I start it using Start-Job -DefinitionName Job-name or by right clicking from Task Scheduler, it works fine but it doesn't start when windows starts.

Currently I am testing this on my personal Windows 10 system, and have checked in another windows 10 system but the behavior remained name. I am attaching screenshot of task scheduler window for this job. enter image description here

Sorry if this questions sounds repeated or dumb (I am a beginner in powershell), but believe me, none of the solutions I found online worked for this.

Thanks in advance !!

Gagan93
  • 1,826
  • 2
  • 25
  • 38
  • what if you check "run with highest privileges"? – SimonS Apr 25 '16 at 17:08
  • even then it doesn't work – Gagan93 Apr 26 '16 at 02:14
  • Try removing the -RandomDelay parameter from your job trigger. Just use -AtStartup and see if it works. – RiverHeart Apr 27 '16 at 01:52
  • Instead of ScheduledJob are you open to ScheduledTask? Can the job run as SYSTEM instead of your user account? If so, I believe I have a solution for you. – Kory Gill Sep 07 '16 at 18:47
  • My answer was deleted here as an identical. So, I only could recommend to look at my answer [here](https://stackoverflow.com/questions/40569045/register-scheduledjob-as-the-system-account-without-having-to-pass-in-credentia/60554216#60554216) as it really doing the thing. – it3xl Apr 15 '20 at 14:02

4 Answers4

18

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."
    }
}
Kory Gill
  • 6,993
  • 1
  • 25
  • 33
  • If the new task principal is SYSTEM, does that mean files created by the automated job will be owned by SYSTEM? I want to run a powershell script at startup as myself but with elevated administrator privileges. The manual way I did it was by running the powershell shell with administrator privileges when logged in as myself and then executing the script. – CMCDragonkai Dec 23 '16 at 06:23
  • 1
    This worked for me, the -Principal fixed my problem. I was trying to create a task for account Administrator via powershell, and was logged on as regular user. The task didn't run even when executing from Task Scheduler manually, and kept saying 'The task has not yet run. (0x41303)' in 'Last Run Result'. Same for Scheduled jobs. And if I edited in Task scheduler it didn't ask for password. Adding the principal param fixed it. Adding '-Credential Administrator' also worked for scheduled job but gave password prompt on creation of task via powershell. – arberg Apr 21 '18 at 10:07
  • @KoryGill I made a small program called `msgbox.exe` and my task scheduler is showing running `0x41301` but there is no Message Box appears. Is it about the program or Just the messagebox utility itself ? – Ahmed Can Unbay Feb 13 '20 at 20:19
  • @arberg what about this – Ahmed Can Unbay Feb 13 '20 at 20:20
  • 1
    @turmuka I do not think scheduled tasks running as system/service account have a desktop where users will see any UI. Searching that error says the task is probably running and my guess is the app is just sitting there waiting (but no one can interact with it to close it). – Kory Gill Feb 14 '20 at 22:18
  • @KoryGill I fixed that issue, but how do i get rid of `Start the task only if AC is on.` through powershell. I think that setting is checked by default, thanks in advance. – Ahmed Can Unbay Feb 19 '20 at 17:37
2

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.

Sencha718
  • 63
  • 1
  • 8
  • This does not provide an answer to the question. Once you have sufficient [reputation](http://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](http://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](http://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/low-quality-posts/13590731) – rpy Sep 07 '16 at 13:17
  • 1
    It does. I suggested to use the "System" account for the task. Which is exactly what the script that someone else posted does as well. This is not a problem with the code. It's the user permissions running it. – Sencha718 Sep 07 '16 at 21:26
  • 1
    Sencha718 has correctly identified the key requirement: the account used to run the job need permission to "log in as a batch job". By default, only the SYSTEM account has this, but its possible to grant the permission to other users, typically through the local security policy. When creating tasks with the ScheduleTasks GUI, this can be done automatically, but it seems that PowerShell doesn't do it. See https://technet.microsoft.com/en-us/itpro/windows/keep-secure/log-on-as-a-batch-job – Burt_Harris Sep 08 '16 at 20:39
0

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)
Upo001
  • 26
  • 3
-1

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: checkbox required checked

Aman Sharma
  • 1,930
  • 1
  • 17
  • 31