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