PowerShell to start a script at startup with Task Scheduler

243 Views Asked by At

I want to automate the running of my AutoHotkey toolkit using Task Scheduler because the "Startup" folder also throws up a CMD screen when it starts, and this method does not. However, I cannot get the below to work. Nothing happens at startup. I then saw that Fast Startup can be an issue (when this is enabled, Windows actually hibernates the kernel, so that a cold boot with not trigger this) so I adjusted the parameters to run when resuming from hibernate. So far nothing works and I don't know where the issue is; I'm hoping that someone with more knowledge of Task Scheduler might have ways to fix this.

# Check if running as administrator
$isAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
if (!$isAdmin) {
    Write-Host "You need to run PowerShell as an administrator to run this script."
    return
}

# Import the required module
Import-Module ScheduledTasks

# Specify the script to run at startup
$action = New-ScheduledTaskAction -Execute 'C:\Program Files\AutoHotkey\AutoHotkey.exe' -Argument 'C:\Users\roysu\OneDrive\0_Scripts_AutoHotKey\Basics-AHK\Basics.ahk'

$trigger = New-ScheduledTaskTrigger -AtStartup   # AtStartup defines when it will happen
$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -DontStopOnIdleEnd -StartWhenAvailable   # Allow the task to be run on demand
$principal = New-ScheduledTaskPrincipal -UserId "NT AUTHORITY\SYSTEM" -LogonType ServiceAccount   # Required for Fast Start situations

# Register the scheduled task
Register-ScheduledTask -TaskName "Run Basics.ahk at Startup" -Action $action -Trigger $trigger -Settings $settings -Description "Run a script at startup" -Principal $principal

2

There are 2 best solutions below

0
Vern_Anderson On

At the top of your script instead of all that code to see if the HOST is elevated, they have created a built in "key word" that does all that for you. Just simply add this comment to the top line of your script.

#Requires -RunAsAdministrator

You can read more about it using "help about_Requires" it works really well and saves writing all that code yourself.

Everything with your scheduled task CMDLETs looks correct and follows the examples perfectly. The onlyt thing I can not duplicate is the autohotkey utility. I know what it is but I do not use it and I do not have it installed.

Is the problem that the task did not get created, or is the problem that it's in the windows task scheduler but is not triggering? You may need to make sure the target machine has autohotkey installed. You could use the Test-Path CMDLET to make sure it is there first. But I would need more details because everything looks correct to me and should be adding the task for you.

0
mklement0 On

Your task, given that it launches an AutoHotkey script, needs to run in the context of your logon sessions (to act on your window station / desktop):

  • Make sure that your task runs at (your) user logon (-AtLogon), not at machine startup
    (-AtStartup):

    • New-ScheduledTaskTrigger -AtLogon
  • Make the task run interactively, with your own user identity:

    • New-ScheduledTaskPrincipal -UserId $env:USERNAME -LogonType Interactive

      • Note: If you choose this option, you should be able to run your task-creation script even without elevation.
    • Alternatively, to make the task run for all (real) users (members of the built-in Users group):

      • $user = New-ScheduledTaskPrincipal -GroupId Users
  • This runs the task visibly in principle on login, but launching an .ahk script (by passing its path as argument to AutoHotkey.exe) in and of itself does not create a visible window (it only adds an icon to the notification area), so this shouldn't be a problem.

    • In general, if your action launches a console-subsystem application, you can hide the console window that is invariably created via a GUI-subsystem helper application that doesn't create a window itself and starts the console application hidden.
      For instance, you can use a helper VBScript launched via wscript.exe, as shown in this answer.

Note that the above means that you don't strictly need to solve your problem with a scheduled task, and the following alternatives should work equally well, using the command-line form of your task action ("C:\Program Files\AutoHotkey\AutoHotkey.exe" "%USERPROFILE%\OneDrive\0_Scripts_AutoHotKey\Basics-AHK\Basics.ahk"):

  • Placing a shortcut file with the command line in the Startup folder ("$env:APPDATA\Microsoft\Windows\Start Menu\Programs\Startup")

  • Creating a value with the command line in the HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run registry key.

That said, as evidenced by the various switches you're passing to New-ScheduledTaskSettingsSet, a scheduled task allows more fine-grained control over the conditions under which the task should run.