Sign in to follow this  
Followers 0

Taskplaner/Taskscheduler COM UDF

47 posts in this topic

#1 ·  Posted (edited)

Hi all,

i needed an UDF for using the Windows Taskplaner / Task Scheduler.

Everything i found was

  • based on at.exe (outdated) or
  • based on schtasks.exe (limited in functionality) or
  • using WMI (which can not see task that were not created with WMI and is also limited)

The only good solution i found was here: http://www.autoit.de/index.php?page=Thread&postID=214517#post214517

But it only had a Create Function.

With my limited knowledge i tried creating more functions and it seems to work quite OK.

You can try it out with TestTaskSchedulerUDF(). WinVista or higher is required.

All feedback is welcome, but please be kind, i do not have much practise and i am well aware that there is room for improvment.

Edit: added new version of the code with more functions:
Edit2: updated UDF fixed bugs
Edit3: added info for multiinst parameter (_TaskCreate)
Edit4: updated UDF (some bugfixes)
Edit5: added version info to UDF, added changes/additions suggested in this thread (_TaskIsEnabled(), _TaskEnable(), _TaskDisable() and $duration for _TaskCreate())
Edit6: added new version that does not use a COM errorhandler (this version can be mixed with other com functions with or without errorhandler, but requires current autoit beta 3.3.9.4 or newer) - see this post for details: (if you do not need other COM routines, there is no need to change from the last version to this one, but all newer version will be without errorhandler...)
Edit7: added version 5.2 with new TaskCreate option $starwhenavailable

Edit8: added version 5.3 fixed versioncompare problems and some typos (now runs with latest beta 3.3.9.22)

As long as there is no feedback this will be the last update...for me it works like it should and i can manage all my tasks just fine!
Keep in Mind that Autoit does not support using more than one ComError Function so be careful if you use other com udfs that need a com errorfunction - this is not a problem when using the taskplanerCOMneh.au3 version (neh=no error handler)


Now we have:

  • Func _TestTaskSchedulerUDF()
  • Func _TaskSchedulerAutostart();check if the schedulerservice is set to autostart
  • Func _TaskIsValidPlatfrom() ;check if os and autoit versions are OK for use with this udf
  • Func _TaskFolderCreate($folder);Create folder - only folders that do not already exist can be created without error
  • Func _TaskFolderDelete($folder);Delete folder - only folders that do exist and that are empty can be deleted without error
  • Func _TaskFolderExists($folder = "");check if a TaskFolder exists
  • Func _TaskExists($taskname, $folder = "");check if a Task exists
  • Func _TaskStop($taskname, $folder = "");stop a task
  • Func _TaskStart($taskname, $folder = "");start a task
  • Func _TaskIsRunning($taskname, $folder = "");check if a Task is running
  • Func _TaskIsEnabled($taskname, $folder = "");check if a Task is enabled
  • Func _TaskEnable($taskname, $folder = "");Enable Task
  • Func _TaskDisable($taskname, $folder = "");Disable Task
  • Func _TaskDelete($taskname, $folder = "");delete an existing task
  • Func _TaskListall($folder = "", $hidden = 1);get a list of all tasks in a given taskfolder (Tasknames only) List is a string with names separeted by "|"
  • Func _TaskCreate($taskname, $TaskDescription, $TriggerEvent, $StartTrigger, $EndTrigger, $DaysOfWeek, $DaysOfMonth, $MonthOfYear, $WeeksOfMonth, $DaysInterval, $Interval, $RepetitionEnabled, $LogonType, $RunLevel, $Username, $Password, $Program, $WorkingDirectory = "", $Arguments = "", $RunOnlyIfNetworkAvailable = True, $active = True, $multiinst = 0, $nobatstart = False, $stoponBat = False, $hidden = False, $idle = False, $WakeToRun = False, $timelimit = "P1D", $priority = 5, $duration="", $StartWhenAvailable = True)

taskplanerudfCOM.au3

taskplanerCOMneh.au3

taskplanerCOMneh5.2.zip

taskplanerCOM_neh5.3.zip

Edited by Allow2010
3 people like this

Share this post


Link to post
Share on other sites



#2 ·  Posted

This topic should probably be in the Example Scripts forum, not the ActiveX/COM Help and Support forum.

P.S. I don't have vista so I can't test it :)

Share this post


Link to post
Share on other sites

#3 ·  Posted (edited)

as this is very fresh and i could very well need some help to improve it, i think it is no yet ready to be an example-)

>WinVista or higher is required.

>>P.S. I don't have vista so I can't test it

hmm, but you probaly have something newer than Vista? Or are you still running W2000/9x?

Edited by Allow2010

Share this post


Link to post
Share on other sites

#4 ·  Posted

hmm, but you probaly have something newer than Vista? Or are you still running W2000/9x?

Nope. :) WinXP

Share this post


Link to post
Share on other sites

#5 ·  Posted

:-) Forgot about XP:-)

Well the COM based method is (IMHO) the best solution as long as no os support below Vista is needed.

I could not find a solution that offers the same possibillities on all OS version.

Share this post


Link to post
Share on other sites

#6 ·  Posted

Update: added more functions to first post

Share this post


Link to post
Share on other sites

#7 ·  Posted (edited)

as i noticed the code is a bit stupid:-)

If one function fails, every function returns a failure...will fix that and post a new version...

Edited by Allow2010

Share this post


Link to post
Share on other sites

#8 ·  Posted

This page here http://msdn.microsoft.com/en-us/library/windows/desktop/aa381341%28v=VS.85%29.aspx

tells me that i can get a returncode

Return value

If this method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.

but $result = $oFolder.CreateFolder($folder) seems to return

[out] ITaskFolder **ppFolder

so any idea how i can get the return code? Thanks !

Share this post


Link to post
Share on other sites

#9 ·  Posted

updates udf in first post.

fixed bugs, changed some names and comments

my question above is still open...help from some com professional is welcome.-)

Share this post


Link to post
Share on other sites

#10 ·  Posted

Updated first post with some info and updated UDF (changed parameter help only)

Share this post


Link to post
Share on other sites

#11 ·  Posted

Share this post


Link to post
Share on other sites

#12 ·  Posted

Allow2010,

Do you want it moved?

M23


Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind._______My UDFs:

ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert - Easily convert date/time formats, including the language used
ExtMsgBox ------------- A highly customisable replacement for MsgBox
GUIExtender ----------- Extend and retract multiple sections within a GUI
GUIFrame -------------- Subdivide GUIs into many adjustable frames
GUIListViewEx -------- Insert, delete, move, drag, sort and edit ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ---------------- Scrolling tickertape GUIs
NoFocusLines --------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify -------------------- Small notifications on the edge of the display
Scrollbars -------------- Automatically sized scrollbars with a single command
StringSize -------------- Automatically size controls to fit text
Toast -------------------- Small GUIs which pop out of the notification area

Share this post


Link to post
Share on other sites

#13 ·  Posted

as i am not sure if it is good enough to be an example, its up to you.-)

Share this post


Link to post
Share on other sites

#14 ·  Posted (edited)

Allow2010,

You will get many more hits here - could help you make it even better. :)

M23

Edited by Melba23
Wrong button too soon!

Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind._______My UDFs:

ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert - Easily convert date/time formats, including the language used
ExtMsgBox ------------- A highly customisable replacement for MsgBox
GUIExtender ----------- Extend and retract multiple sections within a GUI
GUIFrame -------------- Subdivide GUIs into many adjustable frames
GUIListViewEx -------- Insert, delete, move, drag, sort and edit ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ---------------- Scrolling tickertape GUIs
NoFocusLines --------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify -------------------- Small notifications on the edge of the display
Scrollbars -------------- Automatically sized scrollbars with a single command
StringSize -------------- Automatically size controls to fit text
Toast -------------------- Small GUIs which pop out of the notification area

Share this post


Link to post
Share on other sites

#15 ·  Posted (edited)

added new version to first post with some bugfixes/changes for latest AutoIt version

Edited by Allow2010

Share this post


Link to post
Share on other sites

#16 ·  Posted (edited)

I am impressed with your UDF and I think it is much better than schtasks.exe

I want to create a daily task, which

  • starts at 6:30
  • repeats every 6 hours, for a duration of one day
At the moment I can create a daily task which starts at 6:30, repeats every 6 hours but indefinately. I would like to change that to a duration of one day if possible?

_TaskCreate("Smart-Net\SmartRAS Monitor Script", "Report in info about the Smart-RAS to SNID", 2, "2000-01-01T06:30:00", "", "", "", "", "", 1, "PT6H", True, 1, 0, $username,$password, """"&$app&"""", "", "", False, True,0,True,True,False,False,False,"P3D",5)

EDIT

Have modified the UDF to support $Duration

If $RepetitionEnabled Then
  $oTriggerRepetition = $oTrigger.Repetition()
  $oTriggerRepetition.Interval() = $Interval
  $oTriggerRepetition.Duration() = $Duration
 EndIf

Now I am running this code to do what I need

_TaskCreate("Smart-Net\SmartRAS Monitor Script", "Report in info about the Smart-RAS to SNID", 2, "2000-01-01T06:30:00", "", "", "", "", "", 1, "PT6H","P1D", True, 1, 0, $username,$password, """"&$app&"""", "", "", False, True,0,True,True,False,False,False,"P3D",5)

Thanks for the code, its extremely useful. BTW if others want to modify the code I recommend using powershell script here to enumerate the schedule task objects

Edited by NDog

Share this post


Link to post
Share on other sites

#17 ·  Posted

thanks...good addition...

Share this post


Link to post
Share on other sites

#18 ·  Posted

Looks like a useful UDF Allow2010. Thanks ;)

A very small suggestion: The _TaskCreate function has a dayof month parameter which has to be some power of 2. It would be easier (for me at least) if this parameter were just the actual day of the month. To keep it compatible with previous versions you could say that if a negative value is used it means the actual day number (1 - 31). Use -32 for "last day". Then in the function you could have

if $DaysOfMonth < 0 then
 $DaysOfMonth = 2^(-$DaysOfMonth - 1)

Serial port communications UDF Includes functions for binary transmission and reception.printing UDF Useful for graphs, forms, labels, reports etc.Add User Call Tips to SciTE for functions in UDFs not included with AutoIt and for your own scripts.Functions with parameters in OnEvent mode and for Hot Keys One function replaces GuiSetOnEvent, GuiCtrlSetOnEvent and HotKeySet.UDF IsConnected2 for notification of status of connected state of many urls or IPs, without slowing the script.

Share this post


Link to post
Share on other sites

#19 ·  Posted (edited)

Just came across this today and have to say very impressive. Thanks for posting it. There is room for improvement e.g. _TaskSchedulerAutostart() can be consolidated into one line or three if you count Func and EndFunc.

Func _TaskSchedulerAutostart()
    Return RegRead("HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesSchedule", "Start") > 0 ; Returns True or False.
EndFunc   ;==>_TaskSchedulerAutostart
Edited by guinness

UDF List:

 

_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

 

 

Updated: 02/04/2015

Share this post


Link to post
Share on other sites

#20 ·  Posted

Thanks for this, I have been using it successfully wish a few more options were there tho


A true renaissance man

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0