Jump to content

This site uses cookies. By continuing to browse the site you are agreeing to our use of cookies. Find out more here. X
X


Photo

Taskplaner/Taskscheduler COM UDF


  • Please log in to reply
46 replies to this topic

#1 Allow2010

Allow2010

    Prodigy

  • Active Members
  • PipPipPip
  • 197 posts

Posted 26 December 2011 - 04:44 PM

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: http://www.autoitscript.com/forum/topic/138279-com-error-handler-return-values/#entry968768 (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)

Attached Files


Edited by Allow2010, 09 November 2013 - 09:25 PM.

  • mLipok, ModemJunki and AvvA like this







#2 ChrisN

ChrisN

    Wayfarer

  • Active Members
  • Pip
  • 72 posts

Posted 26 December 2011 - 09:15 PM

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 :)

#3 Allow2010

Allow2010

    Prodigy

  • Active Members
  • PipPipPip
  • 197 posts

Posted 26 December 2011 - 09:19 PM

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, 26 December 2011 - 09:19 PM.


#4 ChrisN

ChrisN

    Wayfarer

  • Active Members
  • Pip
  • 72 posts

Posted 26 December 2011 - 11:47 PM

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


Nope. :) WinXP

#5 Allow2010

Allow2010

    Prodigy

  • Active Members
  • PipPipPip
  • 197 posts

Posted 27 December 2011 - 07:41 AM

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

#6 Allow2010

Allow2010

    Prodigy

  • Active Members
  • PipPipPip
  • 197 posts

Posted 27 December 2011 - 08:50 AM

Update: added more functions to first post

#7 Allow2010

Allow2010

    Prodigy

  • Active Members
  • PipPipPip
  • 197 posts

Posted 30 December 2011 - 02:53 PM

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, 24 November 2012 - 09:59 AM.


#8 Allow2010

Allow2010

    Prodigy

  • Active Members
  • PipPipPip
  • 197 posts

Posted 30 December 2011 - 03:23 PM

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 !

#9 Allow2010

Allow2010

    Prodigy

  • Active Members
  • PipPipPip
  • 197 posts

Posted 30 December 2011 - 04:02 PM

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

#10 Allow2010

Allow2010

    Prodigy

  • Active Members
  • PipPipPip
  • 197 posts

Posted 31 December 2011 - 06:57 AM

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

#11 KaFu

KaFu

    Hey, it's just me, KhaFoo...

  • MVPs
  • 3,409 posts

Posted 31 December 2011 - 04:58 PM

Looks really nice :)! And yeah, maybe a Mod better moves this to the example forum.

#12 Melba23

Melba23

    I'm old - what's your excuse?

  • Moderators
  • 22,104 posts

Posted 01 January 2012 - 02:44 PM

Allow2010,

Do you want it moved?

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

#13 Allow2010

Allow2010

    Prodigy

  • Active Members
  • PipPipPip
  • 197 posts

Posted 01 January 2012 - 05:22 PM

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

#14 Melba23

Melba23

    I'm old - what's your excuse?

  • Moderators
  • 22,104 posts

Posted 01 January 2012 - 05:25 PM

Allow2010,

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

M23

Edited by Melba23, 01 January 2012 - 05:25 PM.
Wrong button too soon!

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

#15 Allow2010

Allow2010

    Prodigy

  • Active Members
  • PipPipPip
  • 197 posts

Posted 03 January 2012 - 06:12 PM

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

Edited by Allow2010, 03 January 2012 - 06:13 PM.


#16 NDog

NDog

    Adventurer

  • Active Members
  • PipPip
  • 107 posts

Posted 19 April 2012 - 12:24 AM

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, 19 April 2012 - 02:49 AM.


#17 Allow2010

Allow2010

    Prodigy

  • Active Members
  • PipPipPip
  • 197 posts

Posted 23 April 2012 - 02:29 PM

thanks...good addition...

#18 martin

martin

    ~~\o/~~~/0\=¬''~~~

  • MVPs
  • 7,321 posts

Posted 23 April 2012 - 06:18 PM

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.

#19 guinness

guinness

    all-consuming swarm in inconspicuous disguise

  • Developers
  • 17,659 posts

Posted 17 May 2012 - 11:51 PM

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, 17 May 2012 - 11:56 PM.

Example List: _AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_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()CodingDirToHTML5FileInstallrGeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()LockFile()Mapping CtrlIDsParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...
Updated: 26/09/2014


#20 Attckdog

Attckdog

    Wayfarer

  • Active Members
  • Pip
  • 85 posts

Posted 09 July 2012 - 08:46 PM

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




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users