Jump to content

Sky Slate Blueberry Blackcurrant Watermelon Strawberry Orange Banana Apple Emerald Chocolate
Photo

Create a scheduled task natively [AHK_L]


  • Please log in to reply
12 replies to this topic
shajul
  • Members
  • 571 posts
  • Last active: Aug 01 2015 03:45 PM
  • Joined: 15 Sep 2006
Examples of creating a scheduled task using the Schedule.Service COM class.
Requires: Windows Vista/7/Server 2008

Time based trigger
;------------------------------------------------------------------
; This sample schedules a task to start notepad.exe 30 seconds
; from the time the task is registered.
; Requires AutoHotkey_L
;------------------------------------------------------------------

TriggerType = 1    ; specifies a time-based trigger.
ActionTypeExec = 0    ; specifies an executable action.
LogonType = 3   ; Set the logon type to interactive logon
TaskCreateOrUpdate = 6

;********************************************************
; Create the TaskService object.
service := ComObjCreate("Schedule.Service")
service.Connect()

;********************************************************
; Get a folder to create a task definition in. 
rootFolder := service.GetFolder("\")

; The taskDefinition variable is the TaskDefinition object.
; The flags parameter is 0 because it is not supported.
taskDefinition := service.NewTask(0) 

;********************************************************
; Define information about the task.

; Set the registration info for the task by 
; creating the RegistrationInfo object.
regInfo := taskDefinition.RegistrationInfo
regInfo.Description := "Start notepad at a certain time"
regInfo.Author := "shajul"

;********************************************************
; Set the principal for the task
principal := taskDefinition.Principal
principal.LogonType := LogonType  ; Set the logon type to interactive logon


; Set the task setting info for the Task Scheduler by
; creating a TaskSettings object.
settings := taskDefinition.Settings
settings.Enabled := True
settings.StartWhenAvailable := True
settings.Hidden := False

;********************************************************
; Create a time-based trigger.
triggers := taskDefinition.Triggers
trigger := triggers.Create(TriggerType)

; Trigger variables that define when the trigger is active.
startTime += 30, Seconds  ;start time = 30 seconds from now
FormatTime,startTime,%startTime%,yyyy-MM-ddTHH`:mm`:ss

endTime += 5, Minutes  ;end time = 5 minutes from now
FormatTime,endTime,%endTime%,yyyy-MM-ddTHH`:mm`:ss

trigger.StartBoundary := startTime
trigger.EndBoundary := endTime
trigger.ExecutionTimeLimit := "PT5M"    ;Five minutes
trigger.Id := "TimeTriggerId"
trigger.Enabled := True

;***********************************************************
; Create the action for the task to execute.

; Add an action to the task to run notepad.exe.
Action := taskDefinition.Actions.Create( ActionTypeExec )
Action.Path := "C:\Windows\System32\notepad.exe"

;***********************************************************
; Register (create) the task.
rootFolder.RegisterTaskDefinition("Test TimeTrigger", taskDefinition, TaskCreateOrUpdate ,"","", 3)

MsgBox % "Task submitted.`nstartTime :" . startTime . "`nendTime :" . endTime
Reference: http://msdn.microsof...5(v=VS.85).aspx


Trigger task on boot with highest privileges!
;------------------------------------------------------------------
; This sample schedules a task to start notepad.exe 30 seconds
; after windows boot with highest privileges!.
; Requires AutoHotkey_L
;------------------------------------------------------------------
Gosub RunAsAdministrator

TriggerType = 8   ; trigger on boot.
ActionTypeExec = 0  ; specifies an executable action.
TaskCreateOrUpdate = 6 
Task_Runlevel_Highest = 1 

strUser := "Domain\Username" 
strPassword := "yourpassword" 

objService := ComObjCreate("Schedule.Service") 
objService.Connect() 

objFolder := objService.GetFolder("\") 
objTaskDefinition := objService.NewTask(0) 

principal := objTaskDefinition.Principal 
principal.LogonType := 1    ; Set the logon type to TASK_LOGON_PASSWORD 
principal.RunLevel := Task_Runlevel_Highest  ; Tasks will be run with the highest privileges. 

colTasks := objTaskDefinition.Triggers 
objTrigger := colTasks.Create(TriggerType) 
objTrigger.StartBoundary := "2011-05-27T08:00:00-00:00" 
objTrigger.ExecutionTimeLimit := "PT5M"    ;Five minutes 
colActions := objTaskDefinition.Actions 
objAction := colActions.Create(ActionTypeExec) 
objAction.ID := "Boot Task Test" 
objAction.Path := "C:\Windows\System32\notepad.exe" 
objAction.WorkingDirectory := "C:\Windows\System32" 
objAction.Arguments := "" 
objInfo := objTaskDefinition.RegistrationInfo 
objInfo.Author := "shajul" 
objInfo.Description := "Test task on every boot." 
objSettings := objTaskDefinition.Settings 
objSettings.Enabled := True 
objSettings.Hidden := False 
objSettings.StartWhenAvailable := True 
objFolder.RegisterTaskDefinition("Test Boot Trigger", objTaskDefinition, TaskCreateOrUpdate , strUser, strPassword, 1 )
MsgBox Task Created
ExitApp

RunAsAdministrator:
ShellExecute := A_IsUnicode ? "shell32\ShellExecute":"shell32\ShellExecuteA"
if not A_IsAdmin
{
    If A_IsCompiled
       DllCall(ShellExecute, uint, 0, str, "RunAs", str, A_ScriptFullPath, str, params , str, A_WorkingDir, int, 1)
    Else
       DllCall(ShellExecute, uint, 0, str, "RunAs", str, A_AhkPath, str, """" . A_ScriptFullPath . """" . A_Space . params, str, A_WorkingDir, int, 1)
    ExitApp
}
return

The constants that can be used are listed here for easy inclusion:
;; Ref: http://msdn.microsoft.com/en-us/library/aa383602(v:=vs.85).aspx
 
;; ACTION: Defines the type of actions that a task can perform.
  TASK_ACTION_EXEC           := 0
  TASK_ACTION_COM_HANDLER    := 5
  TASK_ACTION_SEND_EMAIL     := 6
  TASK_ACTION_SHOW_MESSAGE   := 7
 
;; COMPATIBILITY: Defines what versions of Task Scheduler or the AT command that the task is compatible with.
  TASK_COMPATIBILITY_AT   := 0
  TASK_COMPATIBILITY_V1   := 1
  TASK_COMPATIBILITY_V2   := 2 
 
;; TASK_CREATION: Defines how the Task Scheduler service creates updates or disables the task.
  TASK_VALIDATE_ONLY                  := 0x1
  TASK_CREATE                         := 0x2
  TASK_UPDATE                         := 0x4
  TASK_CREATE_OR_UPDATE               := 0x6
  TASK_DISABLE                        := 0x8
  TASK_DONT_ADD_PRINCIPAL_ACE         := 0x10
  TASK_IGNORE_REGISTRATION_TRIGGERS   := 0x20 
 
;; TASK_ENUM_FLAGS: Defines how the Task Scheduler enumerates through registered tasks.
  TASK_ENUM_HIDDEN   := 0x1
 
;; TASK_INSTANCES: Defines how the Task Scheduler handles existing instances of the task when it starts a new instance of the task.
  TASK_INSTANCES_PARALLEL        := 0
  TASK_INSTANCES_QUEUE           := 1
  TASK_INSTANCES_IGNORE_NEW      := 2
  TASK_INSTANCES_STOP_EXISTING   := 3  
 
;; TASK_LOGON: Defines what logon technique is required to run a task.
  TASK_LOGON_NONE                            := 0
  TASK_LOGON_PASSWORD                        := 1
  TASK_LOGON_S4U                             := 2
  TASK_LOGON_INTERACTIVE_TOKEN               := 3
  TASK_LOGON_GROUP                           := 4
  TASK_LOGON_SERVICE_ACCOUNT                 := 5
  TASK_LOGON_INTERACTIVE_TOKEN_OR_PASSWORD   := 6
 
;; TASK_RUN: Defines how a task is run.
  TASK_RUN_NO_FLAGS              := 0x0
  TASK_RUN_AS_SELF               := 0x1
  TASK_RUN_IGNORE_CONSTRAINTS    := 0x2
  TASK_RUN_USE_SESSION_ID        := 0x4
  TASK_RUN_USER_SID              := 0x 
  
;; TASK_RUNLEVEL: Defines LUA elevation flags that specify with what privilege level the task will be run.
  TASK_RUNLEVEL_LUA       := 0
  TASK_RUNLEVEL_HIGHEST   := 1 
 
;; TASK_STATE: Defines the different states that a registered task can be in.
  TASK_STATE_UNKNOWN    := 0
  TASK_STATE_DISABLED   := 1
  TASK_STATE_QUEUED     := 2
  TASK_STATE_READY      := 3
  TASK_STATE_RUNNING    := 4 
 
;; TASK_TRIGGER_TYPE2: Defines the type of triggers that can be used by tasks.
  TASK_TRIGGER_EVENT                  := 0
  TASK_TRIGGER_TIME                   := 1
  TASK_TRIGGER_DAILY                  := 2
  TASK_TRIGGER_WEEKLY                 := 3
  TASK_TRIGGER_MONTHLY                := 4
  TASK_TRIGGER_MONTHLYDOW             := 5
  TASK_TRIGGER_IDLE                   := 6
  TASK_TRIGGER_REGISTRATION           := 7
  TASK_TRIGGER_BOOT                   := 8
  TASK_TRIGGER_LOGON                  := 9
  TASK_TRIGGER_SESSION_STATE_CHANGE   := 11


closed
  • Members
  • 509 posts
  • Last active: Jan 14 2012 06:14 PM
  • Joined: 07 Feb 2008
Thank you for these scripts it gives me an incentive to look into autohotkey_L because these scripts are really usefull! :)

fragman
  • Members
  • 1591 posts
  • Last active: Nov 12 2012 08:51 PM
  • Joined: 13 Oct 2009
Can you post an example how to create a task that runs under the current user account when the user logs on (similar to autorun). The example you posted appears to require a password, which an AHK script usually doesn't have.

shajul
  • Members
  • 571 posts
  • Last active: Aug 01 2015 03:45 PM
  • Joined: 15 Sep 2006
Just Change (untested)

;Gosub RunAsAdministrator ;;comment out
..
principal.RunLevel := TASK_RUNLEVEL_LUA
..

objFolder.RegisterTaskDefinition("Test Boot Trigger", objTaskDefinition, TaskCreateOrUpdate , "", "", TASK_LOGON_INTERACTIVE_TOKEN)

The constants are given below
;; Ref: http://msdn.microsoft.com/en-us/library/aa383602(v=vs.85).aspx
 
;; ACTION: Defines the type of actions that a task can perform.
  TASK_ACTION_EXEC           := 0
  TASK_ACTION_COM_HANDLER    := 5
  TASK_ACTION_SEND_EMAIL     := 6
  TASK_ACTION_SHOW_MESSAGE   := 7
 
;; COMPATIBILITY: Defines what versions of Task Scheduler or the AT command that the task is compatible with.
  TASK_COMPATIBILITY_AT   := 0
  TASK_COMPATIBILITY_V1   := 1
  TASK_COMPATIBILITY_V2   := 2 
 
;; TASK_CREATION: Defines how the Task Scheduler service creates updates or disables the task.
  TASK_VALIDATE_ONLY                  := 0x1
  TASK_CREATE                         := 0x2
  TASK_UPDATE                         := 0x4
  TASK_CREATE_OR_UPDATE               := 0x6
  TASK_DISABLE                        := 0x8
  TASK_DONT_ADD_PRINCIPAL_ACE         := 0x10
  TASK_IGNORE_REGISTRATION_TRIGGERS   := 0x20 
 
;; TASK_ENUM_FLAGS: Defines how the Task Scheduler enumerates through registered tasks.
  TASK_ENUM_HIDDEN   := 0x1
 
;; TASK_INSTANCES: Defines how the Task Scheduler handles existing instances of the task when it starts a new instance of the task.
  TASK_INSTANCES_PARALLEL        := 0
  TASK_INSTANCES_QUEUE           := 1
  TASK_INSTANCES_IGNORE_NEW      := 2
  TASK_INSTANCES_STOP_EXISTING   := 3  
 
;; TASK_LOGON: Defines what logon technique is required to run a task.
  TASK_LOGON_NONE                            := 0
  TASK_LOGON_PASSWORD                        := 1
  TASK_LOGON_S4U                             := 2
  TASK_LOGON_INTERACTIVE_TOKEN               := 3
  TASK_LOGON_GROUP                           := 4
  TASK_LOGON_SERVICE_ACCOUNT                 := 5
  TASK_LOGON_INTERACTIVE_TOKEN_OR_PASSWORD   := 6
 
;; TASK_RUN: Defines how a task is run.
  TASK_RUN_NO_FLAGS              := 0x0
  TASK_RUN_AS_SELF               := 0x1
  TASK_RUN_IGNORE_CONSTRAINTS    := 0x2
  TASK_RUN_USE_SESSION_ID        := 0x4
  TASK_RUN_USER_SID              := 0x 
  
;; TASK_RUNLEVEL: Defines LUA elevation flags that specify with what privilege level the task will be run.
  TASK_RUNLEVEL_LUA       := 0
  TASK_RUNLEVEL_HIGHEST   := 1 
 
;; TASK_STATE: Defines the different states that a registered task can be in.
  TASK_STATE_UNKNOWN    := 0
  TASK_STATE_DISABLED   := 1
  TASK_STATE_QUEUED     := 2
  TASK_STATE_READY      := 3
  TASK_STATE_RUNNING    := 4 
 
;; TASK_TRIGGER_TYPE2: Defines the type of triggers that can be used by tasks.
  TASK_TRIGGER_EVENT                  := 0
  TASK_TRIGGER_TIME                   := 1
  TASK_TRIGGER_DAILY                  := 2
  TASK_TRIGGER_WEEKLY                 := 3
  TASK_TRIGGER_MONTHLY                := 4
  TASK_TRIGGER_MONTHLYDOW             := 5
  TASK_TRIGGER_IDLE                   := 6
  TASK_TRIGGER_REGISTRATION           := 7
  TASK_TRIGGER_BOOT                   := 8
  TASK_TRIGGER_LOGON                  := 9
  TASK_TRIGGER_SESSION_STATE_CHANGE   := 11

If i've seen further it is by standing on the shoulders of giants

my site | ~shajul | WYSIWYG BBCode Editor

fragman
  • Members
  • 1591 posts
  • Last active: Nov 12 2012 08:51 PM
  • Joined: 13 Oct 2009
Thanks. Does this mean I can also run it with TASK_RUNLEVEL_HIGHEST and without password if my current AHK script has Admin permissions?

Edit: Tried it and it works. However, there are some settings in the task scheduler that bother me.

Under conditions, there is one that would stop it when running on batteries, and in preferences or settings (using german windows, can't tell), there are 2 settings that would stop it after 3 days or when it doesn't respond to a close message. Any idea how to turn those off? I'll take a look in msdn and see if I can find these settings, but I haven't been able to find much outside of msdn yet.

shajul
  • Members
  • 571 posts
  • Last active: Aug 01 2015 03:45 PM
  • Joined: 15 Sep 2006

TASK_RUN_IGNORE_CONSTRAINTS
The task is run regardless of constraints such as "do not run on batteries" or "run only if idle".


If i've seen further it is by standing on the shoulders of giants

my site | ~shajul | WYSIWYG BBCode Editor

fragman
  • Members
  • 1591 posts
  • Last active: Nov 12 2012 08:51 PM
  • Joined: 13 Oct 2009
I think that TASK_RUN_FLAGS are only used for IRegisteredTask::RunEx().
Nevermind, I have set all options in a way that shouldn't stop it from running the task. I will post the example soon.

After some more testing, I came up with these methods for creating/deleting/querying a task that runs a program elevated on logon (to avoid UAC dialogs which would be encountered when running it through registry "Run" key or Autorun folder (which might not even work when the program has the execution level specified in its manifest)):

IsAutorunEnabled()
{
	objService := ComObjCreate("Schedule.Service") 
	objService.Connect()
	objFolder := objService.GetFolder("\")
	objTask := objFolder.GetTask("7plus Autorun")
	return objTask.Name != ""
}
DisableAutorun()
{
	objService := ComObjCreate("Schedule.Service") 
	objService.Connect()
	objFolder := objService.GetFolder("\")
	objFolder.DeleteTask("7plus Autorun", 0)
}
EnableAutorun()
{
	if(IsAutorunEnabled())
		return
	TriggerType = 9   ; trigger on logon. 
	ActionTypeExec = 0  ; specifies an executable action. 
	TaskCreateOrUpdate = 6 
	Task_Runlevel_Highest = 1 

	objService := ComObjCreate("Schedule.Service") 
	objService.Connect() 

	objFolder := objService.GetFolder("\") 
	objTaskDefinition := objService.NewTask(0) 

	principal := objTaskDefinition.Principal 
	principal.LogonType := 1    ; Set the logon type to TASK_LOGON_PASSWORD 
	principal.RunLevel := Task_Runlevel_Highest  ; Tasks will be run with the highest privileges. 

	colTasks := objTaskDefinition.Triggers 
	objTrigger := colTasks.Create(TriggerType) 
	colActions := objTaskDefinition.Actions 
	objAction := colActions.Create(ActionTypeExec) 
	objAction.ID := "7plus Autorun" 
	if(A_IsCompiled)
		objAction.Path := """" A_ScriptFullPath """"
	else
	{
		objAction.Path := """" A_AhkPath """"
		objAction.Arguments := """" A_ScriptFullPath """"
	}
	objAction.WorkingDirectory := A_ScriptDir
	objInfo := objTaskDefinition.RegistrationInfo 
	objInfo.Author := "7plus" 
	objInfo.Description := "Run 7plus through task scheduler to prevent UAC dialog." 
	objSettings := objTaskDefinition.Settings 
	objSettings.Enabled := True 
	objSettings.Hidden := False 
	objSettings.StartWhenAvailable := True 
	objSettings.ExecutionTimeLimit := "PT0S"
	objSettings.DisallowStartIfOnBatteries := False
	objSettings.StopIfGoingOnBatteries := False
	objFolder.RegisterTaskDefinition("7plus Autorun", objTaskDefinition, TaskCreateOrUpdate , "", "", 3 ) 
}

Adjust names, ID and author to your case.

haichen
  • Members
  • 200 posts
  • Last active: Oct 20 2013 01:14 PM
  • Joined: 05 Feb 2007

Hi, I tried to get some Scheduler Infos and so far I get this to run. Now I want to retrieve Author, starttime and Stoptime and maybe some others. Hopefully someone can give me a hint.

MsgBox,% GetTaskInfos()
return
ExitApp

GetTaskInfos()
{
    objService := ComObjCreate("Schedule.Service")
    objService.Connect()
    rootFolder := objService.GetFolder("\")
    taskCollection := rootFolder.GetTasks(0)
    numberOfTasks := taskCollection.Count
    ; ?RegistrationInfo.Author
    For registeredTask, state in taskCollection
    {
        if (registeredTask.state == 0)
            state:= "Unknown"
        else if (registeredTask.state == 1)
            state:= "Disabled"
        else if (registeredTask.state == 2)
            state:= "Queued"
        else if (registeredTask.state == 3)
            state:= "Ready"
        else if (registeredTask.state == 4)
            state:= "Running"
        tasklist .= registeredTask.Name "=" state "=" registeredTask.state "`n"
    }
    return tasklist
}
 


jsmain
  • Members
  • 126 posts
  • Last active: Oct 19 2017 01:45 AM
  • Joined: 11 Jul 2005

Thanks for this topic. Using the examples above I was able to create a script that helps you create a task and a shortcut that elevates an app or script to run at the highest privilges, without turning off, or being prompted by the UAC.

 

This script automates the following process...

http://www.sevenforu...mpt-create.html

 

I share it to you here.

; Program Elevator
; AutoHotkey Version: 1.1.10.01
; Language:       	English
; Platform:       	Windows
; Author:         	Jeff Main <Jeff.Main@Gmail.com>
; Revision:			August 20, 2013
;
; Script Function:
;	This script creates an elevated UAC shortcut when executed.
;	Uses Task Scheduler 2.0 API included in Windows Vista and higher. Therefore, not compatible, or necessary for Win XP
;	Just follow steps in initial dialog to 1: Name shortcut/task, 2: choose the executable 
;	file to elevate, 3: set additional launch options, and 4: go!
; * Environment
	#SingleInstance, Force
	RunAsAdmin()
	#NoEnv  ; Recommended for performance and compatibility with future AutoHotkey releases.
	SendMode Input  ; Recommended for new scripts due to its superior speed and reliability.
	SetWorkingDir %A_ScriptDir%  ; Ensures a consistent starting directory.
	SetTitleMatchMode, 2
	DetectHiddenText, On ; -*
; Create Gui *
	if A_OSVersion not in WIN_VISTA,WIN_7,WIN_8  ; Note: No spaces around commas. *
	{	MsgBox This script requires Windows Vista, Windows 7 or Windows 8.
		ExitApp
	} ; -*
	GUI, Font, s11, Verdana  
	GUI, Add, Text, x12 y10 cBlue, This task and shortcut can only be created`, and work`, while logged in as an administrator.`nIt cannot be created in a standard user account!
	GUI, Font, s10, Verdana  
	GUI, Add, Text, x12 y52 h20, 1: Name your shortcut:
	GUI, Add, Edit, x170 y51 w200 h22 vShortcutName,
		GUI, Add, Text, x12 y80 h20, 2: Select the file to execute with this shortcut:
		GUI, Add, Button, x333 y77 w100 h22 gBrowseEXE, Browse...
		GUI, Add, Edit, x30 y105 w718 h22 vFile2Elevate,
	GUI, Add, Text, x12 y135 h20, 3: Optional
	GUI, Add, Text, x30 y155 h20, Additional Arguments (aka additional file to open using above executable)
	GUI, Add, Edit, x30 y175 w610 h22 vFileArgs,
	GUI, Add, Button, x648 y175 w100 h22 gBrowseArg, Browse...
		GUI, Add, Text, x30 y200 h20, Startup Folder
		GUI, Add, Edit, x30 y220 w610 h22 vFileStart,
		GUI, Add, Button, x648 y220 w100 h22 gBrowseStart, Browse...
	GUI, Add, Text, x30 y245 h20, Shortcut Icon File. (may be .ico, .exe, or .dll)
	GUI, Add, Edit, x30 y265 w610 h22 vFileIcon,
	GUI, Add, Button, x648 y265 w100 h22 gBrowseIcon, Browse...
		GUI, Add, Text, x12 y302 h25, 4:
		GUI, Add, Button, x30 y294 w718 h35 gGo, Create task, and Elevated shortcut!
	GUI, Show, xCenter y5 h341 w760 , Create an Elevated Task shortcut.
Return ; -*
BrowseEXE: ; *
	FileSelectFile, SelectedFile, 3, , Open a file, Scripts/Executables (*.ahk; *.exe)
	GuiControl,, File2Elevate, %SelectedFile%
Return ; -*
BrowseArg: ; *
	FileSelectFile, ArgFile, 3, , Open a file, All Documents (*.*)
	GuiControl,, FileArgs, %ArgFile%
Return ; -*
BrowseStart: ; *
	FileSelectFolder, SelectedFolder, , , Select Startup Folder, All Documents (*.*)
	GuiControl,, FileStart, %SelectedFolder%
Return ; -*
BrowseIcon: ; *
	FileSelectFile, SelectedIconFile, 3, , Open a file, Scripts/Executables (*.ico; *.exe; *.dll)
	GuiControl,, FileIcon, %SelectedIconFile%
Return ; -*
Go: ;*
	GuiControlGet, Name, , ShortcutName 
	If Not Name 
	{	MsgBox Please enter a shortcut name!
		Return
	}
	GuiControlGet, File, , File2Elevate 
	If Not File
	{	MsgBox Please enter a File to elevate!
		return
	}
	GuiControlGet, Args, , FileArgs 
	GuiControlGet, Start, , FileStart 
	Path = SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\Tree\Elevate\%Name%
	RegRead,Exist,HKLM, %Path%, Id
	If ErrorLevel ; Should error if no key exists, meaning no duplicate, so we can create the new task.
		GoSub CreateTask
	Else
		GoSub Duplicate
Return ; -*
Duplicate: ; *
	msgbox, 0x60013, Title, Duplicate Task.`nWould you like to Overwrite/Update this task?
	IfMsgBox No
		Return ; allow for changes in task name
	IfMsgBox Cancel
		ExitApp	; else overwrite/update task. -*
CreateTask: ; *
	GUI, Destroy
	SubFolder :=
	IfInString, Name, \
	{ 	StringGetPos, Position, Name, \,R1
		Position := Position + 1
		Len := StrLen(Name)
		If (Len > Position)
		{	StringLeft, SubFolder, Name, Position
			stringRight, Name, Name, Len - Position
		}
	}
	Task := "Elevate\" . SubFolder . Name
	ActionTypeExec = 0  ; specifies an executable action. 
	TaskCreateOrUpdate = 6 
	Task_Runlevel_Highest = 1 
	objService := ComObjCreate("Schedule.Service") 
	objService.Connect() 
	objFolder := objService.GetFolder("\") ; Get task root folder
	objTaskDefinition := objService.NewTask(0) 
	principal := objTaskDefinition.Principal 
	principal.LogonType := 1    ; Set the logon type to TASK_LOGON_PASSWORD 
	principal.RunLevel := Task_Runlevel_Highest  ; Tasks will be run with the highest privileges. 
	colTasks := objTaskDefinition.Triggers 
	colActions := objTaskDefinition.Actions 
	objAction := colActions.Create(ActionTypeExec) 
	objAction.ID := Name 
	objAction.Path := File
	objAction.Arguments := Args
	objAction.WorkingDirectory := Start
	objInfo := objTaskDefinition.RegistrationInfo 
	objInfo.Author := "jsmain" 
	objInfo.Description := "Run program without UAC dialog." 
	objSettings := objTaskDefinition.Settings 
	objSettings.Enabled := True 
	objSettings.Hidden := True 
	objSettings.StartWhenAvailable := True 
	objSettings.ExecutionTimeLimit := "PT0S"
	objSettings.DisallowStartIfOnBatteries := False
	objSettings.StopIfGoingOnBatteries := False
	objFolder.RegisterTaskDefinition(Task, objTaskDefinition, TaskCreateOrUpdate , "", "", 3 ) 
	; Task built, now create a shortcut here
	Target = C:\Windows\System32\schtasks.exe
	LinkFile = %A_ScriptDir%\%Name%.lnk
	Working = 
	RunArgs = /run /tn "Elevate\%SubFolder%%Name%"
	Description := "Run " . Name . " as Administrator, without UAC prompt."
	IconFile = %SelectedIconFile%
	ShortcutKey = 
	IconNum = 1
	RunState = 7	
	FileCreateShortcut, %Target%, %LinkFile%, %Working%, %RunArgs%, %Description%, %IconFile%, %ShortcutKey%, %IconNum%, %RunState%
	ExitApp
Return ; -*
GuiClose: ; *
	ExitApp ; -*
RunAsAdmin() ; *
{	Loop, %0%  ; For each parameter:
	{	param := %A_Index%  ; Fetch the contents of the variable whose name is contained in A_Index.
		params .= A_Space . param
	}
	ShellExecute := A_IsUnicode ? "shell32\ShellExecute":"shell32\ShellExecuteA"
	if not A_IsAdmin
	{	If A_IsCompiled
			DllCall(ShellExecute, uint, 0, str, "RunAs", str, A_ScriptFullPath, str, params , str, A_WorkingDir, int, 1)
		Else
			DllCall(ShellExecute, uint, 0, str, "RunAs", str, A_AhkPath, str, """" . A_ScriptFullPath . """" . A_Space . params, str, A_WorkingDir, int, 1)
		ExitApp
	}
}	; -*

Jeff Main

Albireo
  • Members
  • 558 posts
  • Last active: Jul 13 2017 10:14 AM
  • Joined: 01 Feb 2006

Thanks jsmain!

It was easy to use your program "Elevator" and it works fine.

 

However, if the scheduler for a program is already created.
How do you run that task?
Make a shortcut?

 

I have tried

Run "schtasks /run /tn TaskName",,Max,LabelPID

But it doesn't work

 

//Jan



Albireo
  • Members
  • 558 posts
  • Last active: Jul 13 2017 10:14 AM
  • Joined: 01 Feb 2006

Excuse me!

I found a solution.

Run "c:\windows\system32\schtasks /run /tn TaskName",,Max,LabelPID

or

Run %command% /c "schtasks /run /tn TaskName",,Max,LabelPID

anyway, thanks for "Elevator"!

//Jan



Albireo
  • Members
  • 558 posts
  • Last active: Jul 13 2017 10:14 AM
  • Joined: 01 Feb 2006

But the "LabelPID" is for the "TaskName" schedule, not for the program as started by the "TaskName"

 

I have no idea how to get the PID of the launched application of the "TaskName"

 

//Jan



jsmain
  • Members
  • 126 posts
  • Last active: Oct 19 2017 01:45 AM
  • Joined: 11 Jul 2005

My apologies for not visiting recently.

 

Thanks Albireo!

 

The interface that displays provides everything necessary to create a shortcut for an elevated task. If you create a task that will be a duplicate, there should be a prompt pop up to ask permission to overwrite or rename the task. It's been a while since I poked my head into this code, so I'm a bit rusty with it. If you still have trouble though, I'll try to help.


Jeff Main