mLipok

Check if script is running from TaskScheduler

18 posts in this topic

#1 ·  Posted

I was trying to find a way to check if process is run manually by loged in user or by TaskScheduler.

I find this example:
https://www.autoitscript.com/wiki/Snippets_(_Windows_OS_)#IsDeskTopLocked.28.29
 

but this is not what I looking for, so I decide to ask here.

How to check if script is run from TaskScheduler ?


NEW:     ADO.au3 UDF     POP3.au3 UDF     XML.au3 UDF    How to use IE.au3  UDF with  AutoIt v3.3.14.x  for other useful stuff click the following button:

Spoiler

Last update: 2016-11-12
Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. 

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft Components * TeamViewer API -UDF * JavaManagement UDF * VIES over SOAPPOP3.au3 UDF *  RTF Printer - UDF * XML.au3 - BETA * ADO.au3 UDF SMTP Mailer UDF * WinSCP UDF *

My contribution to others projects: * _sql.au3 UDF  *

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Best coding practices * 

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities *

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, The Art of Computer Programming
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

 

Share this post


Link to post
Share on other sites



#2 ·  Posted (edited)

Sorry, but are you trying to find out basically who ran a process?

Edit:
Perhaps this may help in your endeavors.

Wishing you the best,
Aareon

Edited by Aareon

Share this post


Link to post
Share on other sites

#3 ·  Posted

I know who run. In most cases This User which setup scheduler.

I Just need to know if it is run as a task scheduler job.


NEW:     ADO.au3 UDF     POP3.au3 UDF     XML.au3 UDF    How to use IE.au3  UDF with  AutoIt v3.3.14.x  for other useful stuff click the following button:

Spoiler

Last update: 2016-11-12
Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. 

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft Components * TeamViewer API -UDF * JavaManagement UDF * VIES over SOAPPOP3.au3 UDF *  RTF Printer - UDF * XML.au3 - BETA * ADO.au3 UDF SMTP Mailer UDF * WinSCP UDF *

My contribution to others projects: * _sql.au3 UDF  *

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Best coding practices * 

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities *

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, The Art of Computer Programming
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

 

Share this post


Link to post
Share on other sites

#4 ·  Posted (edited)

Hello mLipok. You can do something like this.

Edit: Require Admin

#AutoIt3Wrapper_Au3Check_Parameters=-q -d -w 1 -w 2 -w 3 -w- 4 -w 5 -w 6 -w- 7
#include <MsgBoxConstants.au3>
#include <File.au3>
#include <WinAPIFiles.au3>
#include <WinAPIProc.au3>

#AutoIt3Wrapper_UseX64=y

Local $aProcess = ProcessList()



Local $IsScheduled = False
For $i = 1 To $aProcess[0][0]
    $IsScheduled = _IsProcessScheduled($aProcess[$i][1])
    ConsoleWrite(($IsScheduled ? "!" : "+") & StringFormat("%-40s%s", $aProcess[$i][0], $IsScheduled) & @CRLF)
Next

Func _IsProcessScheduled($iProcessPID)
    If Not @AutoItX64 Then _WinAPI_Wow64EnableWow64FsRedirection(False)

    Local $sProcessParentName = _WinAPI_GetProcessName(_WinAPI_GetParentProcess($iProcessPID))
    Local $sProcessFullPath = _WinAPI_GetProcessFileName($iProcessPID)
    Local $IsProcessScheduled = False
    Local $sSubKey = ""
    Local $sTasksFolder = @WindowsDir & "\System32\Tasks"
    Local $i = 1
    Local $sRegPath = "HKEY_LOCAL_MACHINE" & (@AutoItX64 ? "" : "64") & "\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\Tasks\"
    Local $sTaskPath = ""
    Local $sXMLTaskPath = ""
    Local $sXMLProcessPath = ""
    While True
        $sSubKey = RegEnumKey($sRegPath, $i)
        $sTaskPath = RegRead($sRegPath & $sSubKey, "Path")
        $sXMLTaskPath = $sTasksFolder & $sTaskPath
        If @error Then ExitLoop
        $sXMLProcessPath = _GetXmlPath(FileRead($sXMLTaskPath))
        If $sXMLProcessPath = $sProcessFullPath Then
            $IsProcessScheduled = True
            ExitLoop
        EndIf
        $i += 1
    WEnd

    If Not @AutoItX64 Then _WinAPI_Wow64EnableWow64FsRedirection(True)

    Return ($IsProcessScheduled And $sProcessParentName = "svchost.exe")
EndFunc   ;==>_IsProcessScheduled


Func _GetXmlPath($sXML)
    Local $sPath = _GetXMLItem($sXML, "Command")
    If StringInStr($sPath, "%") Then
        Local $aReg = StringRegExp($sPath, "%(.*?)%", 3)
        If IsArray($aReg) Then
            $sPath = StringReplace($sPath, "%" & $aReg[0] & "%", EnvGet($aReg[0]))
        EndIf
    EndIf

    Return StringReplace($sPath, '"', '')
EndFunc   ;==>_GetXmlPath


Func _GetXMLItem($sXML, $sItem)
    Local $aReg = StringRegExp($sXML, '<' & $sItem & '>(.*?)</' & $sItem & '>', 3)
    If IsArray($aReg) Then
        Return $aReg[0]
    Else
        Return ""
    EndIf
EndFunc   ;==>_GetXMLItem

Saludos

Edited by Danyfirex
Info

Share this post


Link to post
Share on other sites

#5 ·  Posted

I think I will do it thanks to:

and with this:

https://msdn.microsoft.com/en-us/library/windows/desktop/aa381190(v=vs.85).aspx

 

 


NEW:     ADO.au3 UDF     POP3.au3 UDF     XML.au3 UDF    How to use IE.au3  UDF with  AutoIt v3.3.14.x  for other useful stuff click the following button:

Spoiler

Last update: 2016-11-12
Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. 

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft Components * TeamViewer API -UDF * JavaManagement UDF * VIES over SOAPPOP3.au3 UDF *  RTF Printer - UDF * XML.au3 - BETA * ADO.au3 UDF SMTP Mailer UDF * WinSCP UDF *

My contribution to others projects: * _sql.au3 UDF  *

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Best coding practices * 

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities *

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, The Art of Computer Programming
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

 

Share this post


Link to post
Share on other sites

#6 ·  Posted (edited)

@mLipok, sorry for the late reply. i encountered this issue a while back, and found the most appropriate answer here.

excerpt:

Instead of trying to guess how your program was executed, you should have the launcher tell you how they are executing your program. You do this by registering a different command line for each of the scenarios, and then checking for that command line in the program.

EDIT: i would add also, that for me what makes the difference is the user account under which the exe is run. if it's a scheduled task and i configure it to run as SYSTEM, and otherwise it would run under the logged-on user account, that makes a difference for the exe functionality, and is also easily detectable.

 

@Danyfirex, would you mind explain your logic? i see you query the task scheduler to determine the full path to the exe of the checked process, and compare it to the info you get from the process itself. but the fact that they are identical does not necessarily mean the running process is scheduled, it could mean the user double-clicked the same exe in the same path - which is probably the only place in the system where that exe resides.

then you check that the parent is svchost.exe - i know it runs and manages running services, including the task scheduler, but is it the parent of a scheduled task? do you have any reference for that?

 

 

Edited by orbs

Share this post


Link to post
Share on other sites

#7 ·  Posted

OK, just stumbled upon an approach that might just work.

first, you need to enable the event log that is in charge of the tasks scheduler:

Event viewer \ Applications and Services Logs \ Microsoft \ Windows \ TaskScheduler \ Operational

(on my Windows 7 x64 Ultimate. other versions of Windows might have it somewhere else)

highlight that log, then Actions > Enable Log.

once that is enabled, let your script query this log (start with most recent entries) and look for Event ID 129. the description of it reads something as follows:

Task Scheduler launch task "\au3\au3@task" , instance "C:\au3@task.exe"  with process ID 4028.

if your script process ID (@AutoItPID) and full path (@ScriptFullPath or @AutoItExe, i don't know what's the difference) both match the event description, then your are scheduled! :)

B.T.W. i checked it only manually. i used au3@task as an example for a scheduled task, then i checked the processes list to see its the same PID (4028), that is listed in the event description.

 

Share this post


Link to post
Share on other sites

#8 ·  Posted

Hello. @orbs yes. I check for each process and check parent process ( svchost.exe is the parent for any task (As far I tested)) and task path=processPath. All this is based in my own (5 minutes) testing. It does not mean it's strictly right. But you can check by yourself running same exe one by task scheduler and the other manually and you will see that it match only the scheduled one.

I think is better to use mLipok's method.

Saludos

Share this post


Link to post
Share on other sites

#9 ·  Posted (edited)

Here is my example/solution:
 

#include <MsgBoxConstants.au3>
;~ http://www.fixitscripts.com/problems/script-to-check-if-task-in-windows-task-scheduler-has-run
;---------------------------------------------------------
; This sample enumerates through the tasks on the local computer and
; displays their name and state.
;---------------------------------------------------------
; mLipok:  This sample was modified to show how to check if Running Program is run by TaskScheduler
;---------------------------------------------------------


If _Example() Then MsgBox($MB_ICONINFORMATION, 'ATTENTION', 'This program is run from TASK SCHEDULER')

Func _Example()
    Local $bIsRunFromTaskScheduler = False

    Local $strerrors = 0
    ; Create the Task$service object.
    Local $service = ObjCreate("Schedule.service")
    $service.Connect()

    ; Get the task folder that contains the tasks.
    Local $rootFolder = $service.GetFolder("\")

    Local $taskCollection = $rootFolder.GetTasks(0)

    Local $numberOfTasks = $taskCollection.Count

    If $numberOfTasks = 0 Then
        ConsoleWrite("No tasks are registered." & @CRLF)
    Else
        ConsoleWrite("Number of tasks registered: " & $numberOfTasks & @CRLF)

        For $registeredTask In $taskCollection

            If $registeredTask.State = 4 Then
                ConsoleWrite("Task Name: " & $registeredTask.Name & " is running with PID: " & _TaskScheduler_GetRunningTaskPid($registeredTask.Name) & @CRLF)
                If @AutoItPID = _TaskScheduler_GetRunningTaskPid($registeredTask.Name) Then
                    $bIsRunFromTaskScheduler = True
                EndIf
            ElseIf $registeredTask.LastTaskResult = 0 Then
                ConsoleWrite("Task Name: " & $registeredTask.Name & " is all ok" & @CRLF)
            Else
                ConsoleWrite("Task Name: " & $registeredTask.Name & " has Problems" & @CRLF)
                $strerrors += 1
            EndIf
        Next
    EndIf

    If $strerrors Then
        ConsoleWrite("You have problems at least " & $strerrors & @CRLF)
    Else
        ConsoleWrite("All OK" & @CRLF)
    EndIf

    Return $bIsRunFromTaskScheduler
EndFunc   ;==>_Example


Func _TaskScheduler_GetRunningTaskPid($sTaskName)
    Local $service = ObjCreate("Schedule.service")
    $service.Connect()
    Local $runningTasks = $service.GetRunningTasks(1)

    For $runningTask_enum In $runningTasks
        If $runningTask_enum.Name = $sTaskName Then
            ConsoleWrite("Running Task PID:" & $runningTask_enum.EnginePID & @CRLF)
            Return $runningTask_enum.EnginePID
        EndIf
    Next

EndFunc   ;==>_TaskScheduler_GetRunningTaskPid

 

btw.
There is no need for #RequireAdmin

:)

 

EDIT: REMARK: in this example I intentionaly not use AutoIt BestCodingPractice (VariableNames) , my intention was to show how to convert some part of code from this:
http://www.fixitscripts.com/problems/script-to-check-if-task-in-windows-task-scheduler-has-run

 

Edited by mLipok

NEW:     ADO.au3 UDF     POP3.au3 UDF     XML.au3 UDF    How to use IE.au3  UDF with  AutoIt v3.3.14.x  for other useful stuff click the following button:

Spoiler

Last update: 2016-11-12
Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. 

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft Components * TeamViewer API -UDF * JavaManagement UDF * VIES over SOAPPOP3.au3 UDF *  RTF Printer - UDF * XML.au3 - BETA * ADO.au3 UDF SMTP Mailer UDF * WinSCP UDF *

My contribution to others projects: * _sql.au3 UDF  *

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Best coding practices * 

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities *

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, The Art of Computer Programming
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

 

Share this post


Link to post
Share on other sites

#10 ·  Posted

Here is more proper example:

#include <MsgBoxConstants.au3>

If _TaskScheduler_IsStartedByScheduler() Then MsgBox($MB_ICONINFORMATION, 'ATTENTION', 'This program is run from TASK SCHEDULER "Schedule.service"')

Func _TaskScheduler_IsStartedByScheduler()
    ; Create the Task service object.
    Local $oShedulerService = ObjCreate("Schedule.service")
    $oShedulerService.Connect()

    ; Get the task folder that contains the tasks.
    Local $oRootFolder = $oShedulerService.GetFolder("\")

    Local $oTasks_coll = $oRootFolder.GetTasks(0)
    If $oTasks_coll.Count = 0 Then Return False

    For $oRegisteredTask_enum In $oTasks_coll
        If $oRegisteredTask_enum.State = 4 and @AutoItPID = _TaskScheduler_GetRunningTaskPid($oRegisteredTask_enum.Name) Then
            Return True
        EndIf
    Next

    Return False
EndFunc   ;==>_TaskScheduler_IsStartedByScheduler

Func _TaskScheduler_GetRunningTaskPid($sTaskName)
    Local $oShedulerService = ObjCreate("Schedule.service")
    $oShedulerService.Connect()
    Local $oRunningTasks_coll = $oShedulerService.GetRunningTasks(1)

    For $oRunningTask_enum In $oRunningTasks_coll
        If $oRunningTask_enum.Name = $sTaskName Then Return $oRunningTask_enum.EnginePID
    Next
EndFunc   ;==>_TaskScheduler_GetRunningTaskPid

 

1 person likes this

NEW:     ADO.au3 UDF     POP3.au3 UDF     XML.au3 UDF    How to use IE.au3  UDF with  AutoIt v3.3.14.x  for other useful stuff click the following button:

Spoiler

Last update: 2016-11-12
Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. 

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft Components * TeamViewer API -UDF * JavaManagement UDF * VIES over SOAPPOP3.au3 UDF *  RTF Printer - UDF * XML.au3 - BETA * ADO.au3 UDF SMTP Mailer UDF * WinSCP UDF *

My contribution to others projects: * _sql.au3 UDF  *

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Best coding practices * 

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities *

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, The Art of Computer Programming
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

 

Share this post


Link to post
Share on other sites

#11 ·  Posted

Nice. Just another way for fun.

 

#include <WinAPIProc.au3>


If _IsStartedByScheduler() Then MsgBox($MB_ICONINFORMATION, 'ATTENTION', 'This program is run from TASK SCHEDULER "Schedule.service"')



Func _IsStartedByScheduler()
    Local $iPID1 = _WinAPI_GetParentProcess()
    Local $iPID2 = _WinAPI_GetParentProcess($iPID1)

    Return _WinAPI_GetProcessName($iPID1) = "svchost.exe" And _WinAPI_GetProcessName($iPID2) = "services.exe"
EndFunc   ;==>_IsStartedByScheduler

Saludos

1 person likes this

Share this post


Link to post
Share on other sites

#12 ·  Posted (edited)

Aha.

Few days ago I was trying to do this with the same concept as you was provided, but I was using _WinAPI_GetParentProcess() only once :), so I have no positive efects.

 

 

Edited by mLipok

NEW:     ADO.au3 UDF     POP3.au3 UDF     XML.au3 UDF    How to use IE.au3  UDF with  AutoIt v3.3.14.x  for other useful stuff click the following button:

Spoiler

Last update: 2016-11-12
Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. 

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft Components * TeamViewer API -UDF * JavaManagement UDF * VIES over SOAPPOP3.au3 UDF *  RTF Printer - UDF * XML.au3 - BETA * ADO.au3 UDF SMTP Mailer UDF * WinSCP UDF *

My contribution to others projects: * _sql.au3 UDF  *

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Best coding practices * 

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities *

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, The Art of Computer Programming
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

 

Share this post


Link to post
Share on other sites

#13 ·  Posted (edited)

@mLipok,

your example at post #10 does not work for me. i'm in the process troubleshooting.

@Danyfirex,

i found (using Process Explorer) that the parent of a task is taskeng.exe, and its parent is svchost.exe (Windows 7 x64). so your solution at post #11 works if i change it to:

Func _IsStartedByScheduler()
    Local $iPID1 = _WinAPI_GetParentProcess()
    Local $iPID2 = _WinAPI_GetParentProcess($iPID1)

    Return _WinAPI_GetProcessName($iPID1) = "taskeng.exe" And _WinAPI_GetProcessName($iPID2) = "svchost.exe"
EndFunc   ;==>_IsStartedByScheduler

z

 

Edited by orbs

Share this post


Link to post
Share on other sites

#14 ·  Posted (edited)

9 minutes ago, orbs said:

your example at post #10 does not work for me. i'm in the process troubleshooting.

Please try this modified version with COM Error Handler:
 

#include <MsgBoxConstants.au3>

Global $__g_oErrorHandler = ObjEvent("AutoIt.Error", "_ErrFunc")

If _TaskScheduler_IsStartedByScheduler() Then MsgBox($MB_ICONINFORMATION, 'ATTENTION', 'This program is run from TASK SCHEDULER "Schedule.service"')

Func _TaskScheduler_IsStartedByScheduler()
    ; Create the Task service object.
    Local $oShedulerService = ObjCreate("Schedule.service")
    $oShedulerService.Connect()

    ; Get the task folder that contains the tasks.
    Local $oRootFolder = $oShedulerService.GetFolder("\")

    Local $oTasks_coll = $oRootFolder.GetTasks(0)
    If $oTasks_coll.Count = 0 Then Return False

    For $oRegisteredTask_enum In $oTasks_coll
        If $oRegisteredTask_enum.State = 4 and @AutoItPID = _TaskScheduler_GetRunningTaskPid($oRegisteredTask_enum.Name) Then
            Return True
        EndIf
    Next

    Return False
EndFunc   ;==>_TaskScheduler_IsStartedByScheduler

Func _TaskScheduler_GetRunningTaskPid($sTaskName)
    Local $oShedulerService = ObjCreate("Schedule.service")
    $oShedulerService.Connect()
    Local $oRunningTasks_coll = $oShedulerService.GetRunningTasks(1)

    For $oRunningTask_enum In $oRunningTasks_coll
        If $oRunningTask_enum.Name = $sTaskName Then Return $oRunningTask_enum.EnginePID
    Next
EndFunc   ;==>_TaskScheduler_GetRunningTaskPid


; User's COM error function. Will be called if COM error occurs
Func _ErrFunc($oError)
    ; Do anything here.
    Local $sErrorDescription = @ScriptName & " (" & $oError.scriptline & ") : ==> COM Error intercepted !" & @CRLF & _
            @TAB & "$oError.number is: " & @TAB & @TAB & "0x" & Hex($oError.number) & @CRLF & _
            @TAB & "$oError.windescription:" & @TAB & $oError.windescription & @CRLF & _
            @TAB & "$oError.description is: " & @TAB & $oError.description & @CRLF & _
            @TAB & "$oError.source is: " & @TAB & @TAB & $oError.source & @CRLF & _
            @TAB & "$oError.helpfile is: " & @TAB & $oError.helpfile & @CRLF & _
            @TAB & "$oError.helpcontext is: " & @TAB & $oError.helpcontext & @CRLF & _
            @TAB & "$oError.lastdllerror is: " & @TAB & $oError.lastdllerror & @CRLF & _
            @TAB & "$oError.scriptline is: " & @TAB & $oError.scriptline & @CRLF & _
            @TAB & "$oError.retcode is: " & @TAB & "0x" & Hex($oError.retcode) & @CRLF & @CRLF
    ClipPut($sErrorDescription)
    MsgBox($MB_ICONERROR, 'COM Error', $sErrorDescription)
EndFunc   ;==>_ErrFunc

EDIT:
I'm curious whether you will see an error.
If so, paste the message here ( message should be automaticaly saved to clipboard).

 

Edited by mLipok

NEW:     ADO.au3 UDF     POP3.au3 UDF     XML.au3 UDF    How to use IE.au3  UDF with  AutoIt v3.3.14.x  for other useful stuff click the following button:

Spoiler

Last update: 2016-11-12
Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. 

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft Components * TeamViewer API -UDF * JavaManagement UDF * VIES over SOAPPOP3.au3 UDF *  RTF Printer - UDF * XML.au3 - BETA * ADO.au3 UDF SMTP Mailer UDF * WinSCP UDF *

My contribution to others projects: * _sql.au3 UDF  *

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Best coding practices * 

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities *

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, The Art of Computer Programming
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

 

Share this post


Link to post
Share on other sites

#15 ·  Posted

@mLipok,

no COM error.

i added some logging to your function, like this:

Func _TaskScheduler_IsStartedByScheduler()
    ; Create the Task service object.
    Local $oShedulerService = ObjCreate("Schedule.service")
    _Log('$oShedulerService = ' & ObjName($oShedulerService))
    $oShedulerService.Connect()

    ; Get the task folder that contains the tasks.
    Local $oRootFolder = $oShedulerService.GetFolder("\")
    _Log('$oRootFolder = ' & ObjName($oRootFolder))

    Local $oTasks_coll = $oRootFolder.GetTasks(0)
    _Log('$oTasks_coll = ' & ObjName($oTasks_coll))
    _Log('$oTasks_coll.Count = ' & $oTasks_coll.Count)
    If $oTasks_coll.Count = 0 Then Return False

    _Log('@AutoItPID = ' & @AutoItPID)
    For $oRegisteredTask_enum In $oTasks_coll
        _Log('task name = ' & $oRegisteredTask_enum.Name & ' ; task state = ' & $oRegisteredTask_enum.State & ' ; task PID = ' & _TaskScheduler_GetRunningTaskPid($oRegisteredTask_enum.Name))
        If $oRegisteredTask_enum.State = 4 And @AutoItPID = _TaskScheduler_GetRunningTaskPid($oRegisteredTask_enum.Name) Then
            Return True
        EndIf
    Next

    _Log('no match')
    Return False
EndFunc   ;==>_TaskScheduler_IsStartedByScheduler

where _Log() is simply a call to FileWriteLine() with a prefixed file name.

the result (log stripped of the other tasks it found) - the mismatch highlight in red:

$oShedulerService = ITaskService
$oRootFolder = ITaskFolder
$oTasks_coll = IRegisteredTaskCollection
$oTasks_coll.Count = 6
@AutoItPID = 1408
task name = au3@task ; task state = 4 ; task PID = 5204
no match

 

the PID of the script and the PID of the task are different. in Process Explorer i can see why:

au3@task.png

it seems the query returns the PID of the engine (taskeng.exe) running the script, not of the script.

any thoughts?

 

 

Share this post


Link to post
Share on other sites

#16 ·  Posted (edited)

@mLipok the error is that in Windows 7 $oRunningTask_enum.EnginePID returns the PID of the parent. In windows 10 returns the Task PID.

@orbs You right in windows 7 is diferent (I wrote the code in Windows 10. Its diferent) Here is an Updated code that works in Window 7 and Windows 10

 

#include <WinAPIProc.au3>


If _IsStartedByScheduler() Then MsgBox($MB_ICONINFORMATION, 'ATTENTION', 'This program is run from TASK SCHEDULER "Schedule.service"')


Func _IsStartedByScheduler()
    Local $iPID1 = _WinAPI_GetParentProcess()
    Local $iPID2 = _WinAPI_GetParentProcess($iPID1)
    Return StringRegExp(_WinAPI_GetProcessName($iPID1),"taskeng|svchost") and StringRegExp(_WinAPI_GetProcessName($iPID2),"svchost|services")
EndFunc   ;==>_IsStartedByScheduler

 

Saludos

Edited by Danyfirex

Share this post


Link to post
Share on other sites

#17 ·  Posted

ah, yet another one of Windows 10 "improvements"! :'(

so this means that whichever method we work with the Task Scheduler should be thoroughly tested on every version, edition, update and architecture of Windows.

that's just great.

1 person likes this

Share this post


Link to post
Share on other sites

#18 ·  Posted

19 minutes ago, orbs said:

that's just great.

After all it is normal testing procedure, check your program on all target systems.


NEW:     ADO.au3 UDF     POP3.au3 UDF     XML.au3 UDF    How to use IE.au3  UDF with  AutoIt v3.3.14.x  for other useful stuff click the following button:

Spoiler

Last update: 2016-11-12
Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. 

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft Components * TeamViewer API -UDF * JavaManagement UDF * VIES over SOAPPOP3.au3 UDF *  RTF Printer - UDF * XML.au3 - BETA * ADO.au3 UDF SMTP Mailer UDF * WinSCP UDF *

My contribution to others projects: * _sql.au3 UDF  *

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Best coding practices * 

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities *

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, The Art of Computer Programming
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

 

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