Sign in to follow this  
Followers 0
fusion400

Execute bat exactly like it would have in windows autostart folder?

2 posts in this topic

Hello does anyone know the best practice of executing a bat file exactly like it is done in Windows autostart folder.

When the computer is turned on the bat files are executed by shortcuts located in the autostart folder.

But the apps needs to be restarted every day at 06:00 so i had to make this script to try and control the situation. It also tries to contain several serious issues that causes different applications error to pop up on top of the main application.

My problem is that sometimes the java app seems for no reason to execute one time to many which causes serious issues.

Is there anyway to also control the number of java.exe processes that can be started i would like to have a limit of a maximum of 4 started java.exe processes. When there is more it should kill the one that started last.

Currently my code looks like this:

#include <Misc.au3>
Global $HasRunToday = False
Global $Process = "java.exe" 
;Opt("WinSearchChildren", -1)  
;Opt("WinTitleMatchMode", -2)   
_Singleton("Restart Script")
    
pathtods()
killds() 

Func pathtods()
If FileExists("d:\ds1\ds1.bat") then Global $directory = "d:\"
If FileExists("e:\ds1\ds1.bat") then Global $directory = "e:\"
If FileExists("c:\ds1\ds1.bat") then Global $directory = "c:\"
If FileExists("n:\ds1\ds1.bat") then Global $directory = "n:\"
;MsgBox(0, "", $directory & "ds1\ds1.bat")
EndFunc

Func killds()
While 1
    If @HOUR = 6 And @min = 0 And $HasRunToday = False Then
    _ProcessCloseEx($Process)
        Sleep(66000)
        FileChangeDir($directory & "ds1")
        ;RunWait("ds1.bat")
        ShellExecuteWait("ds1.bat")
        Sleep(1000)
        FileChangeDir($directory & "ds2")
        ;RunWait("ds2.bat")
        ShellExecuteWait("ds2.bat")
        ;RunWait(@ComSpec & ' /k ds1.bat', 'ds1.bat')
        ;RunWait(@COMSPEC & " /c n:\ds1\.bat")
        $HasRunToday = True
    ElseIf @HOUR = 0 and @min = 1 Then
        $HasRunToday = False   
        ElseIf WinActive("Print") then       
        Send("!p")
        ElseIf WinExists("Microsoft Visual C++ Runtime Library") then       
        WinClose("Microsoft Visual C++ Runtime Library")   
        ElseIf WinExists("java") then       
        WinClose("java")  
        ElseIf WinExists("Java") then       
        WinClose("Java")  
        ElseIf WinExists("java.exe") then       
        WinClose("java.exe")  
        ElseIf WinExists("VPU Recover") then       
        WinClose("VPU Recover")  
        ElseIf WinExists("java.exe - Application Error") then       
        WinClose("java.exe - Application Error")   
        ElseIf WinExists("logonui.exe - Application Error") then       
        WinClose("logonui.exe - Application Error")   
        ElseIf WinExists("cmd.exe - Application Error") then       
        WinClose("cmd.exe - Application Error")  
        ElseIf WinExists("Java.exe crashed") then       
        WinClose("Java.exe crashed") 
        ElseIf WinExists("java.exe crashed") then       
        WinClose("java.exe crashed")
        ElseIf WinExists("Unexpected Error") then       
        WinClose("Unexpected Error")    
        
    EndIf
    ;FindImage()
    Sleep(1000)
WEnd
EndFunc

Func _ProcessCloseEx($sPID)
    ;If IsString($sPID) Then $sPID = ProcessExists($sPID)
    ;If Not $sPID Then Return SetError(1, 0, 0)
    while ProcessExists($sPID)
        RunWait("taskkill /IM " & $sPID &  " /T")
        Sleep(1000)
        RunWait("taskkill /F /IM " & $sPID &  " /T")
    ;run(@ComSpec & " /c taskkill /IM " & $sPID & " /T", @SystemDir, @SW_HIDE)
    ;run(@ComSpec & " /c taskkill /F /IM " & $sPID & " /T", @SystemDir, @SW_HIDE)
    Sleep(1000)
    WEnd
    ;Return run(@ComSpec & " /c taskkill /F /IM " & $sPID & " /T", @SystemDir, @SW_HIDE)
EndFunc

Share this post


Link to post
Share on other sites



#2 ·  Posted (edited)

Threw together some snippets flying around :mellow:... Look at the array $a_Process_Restrict_Number_Wrapper for the configuration, example allows two notepad.exe process at max while killing new instances, function is called every 1000ms via AdlibRegister(). Kudos to Manko for his work here...

; http://www.autoitscript.com/forum/index.php?showtopic=88934&view=findpost&p=651357
; by Manko

#include <array.au3>    ; Needed to display array in example.

$tag_SYSTEM_THREADS = "double KernelTime;" & _
        "double UserTime;" & _
        "double CreateTime;" & _
        "ulong  WaitTime;" & _
        "ptr    StartAddress;" & _
        "dword  UniqueProcess;" & _
        "dword  UniqueThread;" & _
        "long   Priority;" & _
        "long   BasePriority;" & _
        "ulong  ContextSwitchCount;" & _
        "long   State;" & _
        "long   WaitReason"

$tag_SYSTEM_PROCESSES = "ulong  NextEntryDelta;" & _
        "ulong  Threadcount;" & _
        "ulong[6];" & _                         ; Reserved...
        "double CreateTime;" & _
        "double UserTime;" & _
        "double KernelTime;" & _
        "ushort Length;" & _                    ; unicode string length
        "ushort MaximumLength;" & _             ; also for unicode string
        "ptr    ProcessName;" & _               ; ptr to mentioned unicode string - name of process
        "long   BasePriority;" & _
        "ulong  ProcessId;" & _
        "ulong  InheritedFromProcessId;" & _
        "ulong  HandleCount;" & _
        "ulong[2];" & _                         ;Reserved...
        "uint   PeakVirtualSize;" & _
        "uint   VirtualSize;" & _
        "ulong  PageFaultCount;" & _
        "uint   PeakWorkingSetSize;" & _
        "uint   WorkingSetSize;" & _
        "uint   QuotaPeakPagedPoolUsage;" & _
        "uint   QuotaPagedPoolUsage;" & _
        "uint   QuotaPeakNonPagedPoolUsage;" & _
        "uint   QuotaNonPagedPoolUsage;" & _
        "uint   PagefileUsage;" & _
        "uint   PeakPagefileUsage;" & _
        "uint64 ReadOperationCount;" & _
        "uint64 WriteOperationCount;" & _
        "uint64 OtherOperationCount;" & _
        "uint64 ReadTransferCount;" & _
        "uint64 WriteTransferCount;" & _
        "uint64 OtherTransferCount"

HotKeySet("{ESC}", "_Exit")

; ############ Config ####################
Global $a_ProcessRestrictInstanceNumber[3]
$a_ProcessRestrictInstanceNumber[0] = 2 ; Max number of allowed processs
$a_ProcessRestrictInstanceNumber[1] = "notepad.exe" ; process name, e.g. "explorer.exe"
$a_ProcessRestrictInstanceNumber[2] = 0 ; Kill Older process first, 1=true (0=false, Kill Newer Processes first)

AdlibRegister("_ProcessRestrictInstanceNumber", 1000)
OnAutoItExitRegister("_OnAutoItExit")

; ############ Main Loop ####################
While 1
    Sleep(10)
WEnd
; ############ Main Loop ####################

Func _Exit()
    Exit
EndFunc   ;==>_Exit

Func _OnAutoItExit()
    AdlibUnRegister("_ProcessRestrictInstanceNumber")
EndFunc   ;==>_OnAutoItExit

; ############ Functions ####################

Func _ProcessRestrictInstanceNumber()
    $aProcess = _WinAPI_ThreadnProcess__Single_Process($a_ProcessRestrictInstanceNumber[1])
    If Not @error And IsArray($aProcess) Then
        _ArraySort($aProcess, $a_ProcessRestrictInstanceNumber[2], 1, UBound($aProcess) - 1, 5)
        ;_ArrayDisplay($aProcess, "Createtime example...")
        If UBound($aProcess) > $a_ProcessRestrictInstanceNumber[0] Then
            For $i = $a_ProcessRestrictInstanceNumber[0] + 1 To UBound($aProcess) - 1
                If ProcessExists($aProcess[$i][2]) Then
                    Switch ProcessClose($aProcess[$i][2])
                        Case 1
                            ConsoleWrite("+" & TimerInit() & @TAB & "Closed process " & $a_ProcessRestrictInstanceNumber[1] & " with PID " & $aProcess[$i][2] & @CRLF)
                        Case 0
                            ConsoleWrite("-" & TimerInit() & @TAB & "Falied to close process " & $a_ProcessRestrictInstanceNumber[1] & " with PID " & $aProcess[$i][2] & @CRLF)
                    EndSwitch
                EndIf
            Next
        EndIf
    EndIf
EndFunc   ;==>_ProcessRestrictInstanceNumber


Func _WinAPI_ThreadnProcess__Single_Process($sProcess)
    If Not ProcessExists($sProcess) Then Return SetError(1)

    $time = TimerInit()
    $a_WinAPI_ThreadnProcess__All_Processs = _WinAPI_ThreadnProcess()
    $a_WinAPI_ThreadnProcess__All_Processs[0][0] = "Runtime = " & Round(TimerDiff($time), 2) & "ms"
    $a_WinAPI_ThreadnProcess__All_Processs[0][1] = "PID"
    $a_WinAPI_ThreadnProcess__All_Processs[0][3] = "WorkingSetSize"
    $a_WinAPI_ThreadnProcess__All_Processs[0][2] = "ParentPID"
    $a_WinAPI_ThreadnProcess__All_Processs[0][4] = "IsSuspended"
    $a_WinAPI_ThreadnProcess__All_Processs[0][5] = "CreateTime"
    ;_ArrayDisplay($a_WinAPI_ThreadnProcess__All_Processs, "Createtime example...")

    Dim $a_WinAPI_ThreadnProcess__Single_Processs[1][6]
    For $i = 1 To UBound($a_WinAPI_ThreadnProcess__All_Processs) - 1
        ;ConsoleWrite($a_WinAPI_ThreadnProcess__All_Processs[$i][0] & @CRLF)
        If $a_WinAPI_ThreadnProcess__All_Processs[$i][0] = $sProcess Then

            ReDim $a_WinAPI_ThreadnProcess__Single_Processs[UBound($a_WinAPI_ThreadnProcess__Single_Processs) + 1][6]
            $a_WinAPI_ThreadnProcess__Single_Processs[UBound($a_WinAPI_ThreadnProcess__Single_Processs) - 1][0] = $a_WinAPI_ThreadnProcess__All_Processs[$i][0]
            $a_WinAPI_ThreadnProcess__Single_Processs[UBound($a_WinAPI_ThreadnProcess__Single_Processs) - 1][1] = $a_WinAPI_ThreadnProcess__All_Processs[$i][1]
            $a_WinAPI_ThreadnProcess__Single_Processs[UBound($a_WinAPI_ThreadnProcess__Single_Processs) - 1][2] = $a_WinAPI_ThreadnProcess__All_Processs[$i][2]
            $a_WinAPI_ThreadnProcess__Single_Processs[UBound($a_WinAPI_ThreadnProcess__Single_Processs) - 1][3] = $a_WinAPI_ThreadnProcess__All_Processs[$i][3]
            $a_WinAPI_ThreadnProcess__Single_Processs[UBound($a_WinAPI_ThreadnProcess__Single_Processs) - 1][4] = $a_WinAPI_ThreadnProcess__All_Processs[$i][4]
            $a_WinAPI_ThreadnProcess__Single_Processs[UBound($a_WinAPI_ThreadnProcess__Single_Processs) - 1][5] = $a_WinAPI_ThreadnProcess__All_Processs[$i][5]
        EndIf
    Next
    $a_WinAPI_ThreadnProcess__Single_Processs[0][0] = "Runtime = " & Round(TimerDiff($time), 2) & "ms"
    $a_WinAPI_ThreadnProcess__Single_Processs[0][1] = "PID"
    $a_WinAPI_ThreadnProcess__Single_Processs[0][3] = "WorkingSetSize"
    $a_WinAPI_ThreadnProcess__Single_Processs[0][2] = "ParentPID"
    $a_WinAPI_ThreadnProcess__Single_Processs[0][4] = "IsSuspended"
    $a_WinAPI_ThreadnProcess__Single_Processs[0][5] = "CreateTime"
    ;_ArrayDisplay($a_WinAPI_ThreadnProcess__Single_Processs, "Createtime example...")

    Return $a_WinAPI_ThreadnProcess__Single_Processs

EndFunc   ;==>_WinAPI_ThreadnProcess__Single_Process


; ############ Here be example func! ####################
Func _WinAPI_ThreadnProcess()
    Local $ret = DllCall("ntdll.dll", "int", "ZwQuerySystemInformation", "int", 5, "int*", 0, "int", 0, "int*", 0)
    Local $Mem = DllStructCreate("byte[" & $ret[4] & "]")
    Local $ret = DllCall("ntdll.dll", "int", "ZwQuerySystemInformation", "int", 5, "ptr", DllStructGetPtr($Mem), "int", DllStructGetSize($Mem), "int*", 0)
    Local $SysProc = DllStructCreate($tag_SYSTEM_PROCESSES, $ret[2])
    Local $SysProc_ptr = $ret[2]
    Local $SysProc_Size = DllStructGetSize($SysProc)
    Local $SysThread = DllStructCreate($tag_SYSTEM_THREADS)
    Local $SysThread_Size = DllStructGetSize($SysThread)
    Local $buffer, $i, $lastthread, $m = 0, $NextEntryDelta, $k, $temp, $space, $l
    Local $avArray[10000][7]
    While 1
        ; Get procinfo here
        ; ...
        ; ###### Example...
        ; Get process name. Convert Unicode to string.
        $buffer = DllStructCreate("char[" & DllStructGetData($SysProc, "Length") & "]", DllStructGetData($SysProc, "ProcessName"))
        For $i = 0 To DllStructGetData($SysProc, "Length") - 1 Step 2
            $avArray[$m][0] &= DllStructGetData($buffer, 1, $i + 1)
        Next
        ; ... more data ...
        $avArray[$m][1] = DllStructGetData($SysProc, "ProcessId")
        ;$strString = DllStructCreate ( "wchar[" & DllStructGetData($SysProc, "Length") & "]" , DllStructGetData($SysProc, "ProcessName"))
        ;$avArray[$m][1] = DllStructGetData ($strString, 1)

        $avArray[$m][3] = DllStructGetData($SysProc, "WorkingSetSize") / (1024) & " kB"
        $avArray[$m][2] = DllStructGetData($SysProc, "InheritedFromProcessId")
        $avArray[$m][4] = 1 ; We assume suspended. When we check the threads we change it.
        ;$two=DllStructCreate("dword[2]",DllStructGetPtr($SysProc, "CreateTime"))
        ;msgbox(0,DllStructGetData($two, 1), DllStructGetData($two, 2))
        If DllStructGetData($SysProc, "CreateTime") Then
            $avArray[$m][5] = _WinAPI_FileTimeConvert(DllStructGetData($SysProc, "CreateTime"))
            #cs
                $avArray[$m][5] = StringLeft($avArray[$m][5], 4) & "/" & StringMid($avArray[$m][5], 5, 2) & "/" & StringMid($avArray[$m][5], 7, 2) & _
                " " & StringMid($avArray[$m][5], 9, 2) & ":" & StringMid($avArray[$m][5], 11, 2) & ":" & StringMid($avArray[$m][5], 13, 2)
            #ce
        EndIf
        ; ##### Example ends...

        ; ... over to threads...
        For $i = 0 To DllStructGetData($SysProc, "Threadcount") - 1
            $SysThread = DllStructCreate($tag_SYSTEM_THREADS, $SysProc_ptr + $SysProc_Size + $i * $SysThread_Size)
            ;Get Threadinfo here...
            ; ...
            ; ##### Example...
            ; Check "WaitReason" = 5 = "Suspended". If not. process is not suspended...
            If DllStructGetData($SysThread, "WaitReason") <> 5 Then
                $avArray[$m][4] = 0 ; If just one thread is active... process is not suspended.
                ExitLoop
            EndIf
            ; ##### Example ends...

            ; ... loop to next thread...
        Next
        $NextEntryDelta = DllStructGetData($SysProc, "NextEntryDelta")
        If Not $NextEntryDelta Then ExitLoop
        $SysProc_ptr += $NextEntryDelta
        $SysProc = DllStructCreate($tag_SYSTEM_PROCESSES, $SysProc_ptr)
        $m += 1
        ContinueLoop
    WEnd
    ReDim $avArray[$m + 1][7]
    Return $avArray
EndFunc   ;==>_WinAPI_ThreadnProcess
; ################################ END FUNC ##########################################

; ######################## Ascendants nice filetime-conversion! ######################
Func _WinAPI_FileTimeConvert($iFileDateTime, $DLL = -1)
    Local $sDateTimeStr, $stLocalFileTime, $stFileTime, $stSystemTime, $aRet
    ; FILETIME structures [DateTimeLo,DateTimeHi]
    $stLocalFileTime = DllStructCreate("dword[2]")
    $stFileTime = DllStructCreate("double")
    ; SYSTEMTIME structure [Year,Month,DayOfWeek,Day,Hour,Min,Sec,Milliseconds]
    $stSystemTime = DllStructCreate("ushort;ushort;ushort;ushort;ushort;ushort;ushort;ushort")

    If $DLL == -1 Then $DLL = "Kernel32.dll"
    ; Set the appropriate data members of the FileTime structure
    DllStructSetData($stFileTime, 1, $iFileDateTime, 1)
    ;DllStructSetData($stFileTime, 1, $iFileDateTimeHi, 2)

    ; First convert file time (UTC-based file time) to 'local file time'
    $aRet = DllCall($DLL, "int", "FileTimeToLocalFileTime", "ptr", DllStructGetPtr($stFileTime), "ptr", DllStructGetPtr($stLocalFileTime))
    If @error Or Not IsArray($aRet) Or Not $aRet[0] Then Return SetError(2, 0, "")

    ; Then convert file time to a system time structure
    $aRet = DllCall($DLL, "int", "FileTimeToSystemTime", "ptr", DllStructGetPtr($stLocalFileTime), "ptr", DllStructGetPtr($stSystemTime))
    If @error Or Not IsArray($aRet) Or Not $aRet[0] Then Return SetError(2, 0, "")

    ; Now format it and return it in a string. Format: YYYYMMDDHHSSMM
    $sDateTimeStr = DllStructGetData($stSystemTime, 1) & StringRight('0' & DllStructGetData($stSystemTime, 2), 2) & _
            StringRight('0' & DllStructGetData($stSystemTime, 4), 2) & _
            StringRight('0' & DllStructGetData($stSystemTime, 5), 2) & StringRight('0' & DllStructGetData($stSystemTime, 6), 2) & _
            StringRight('0' & DllStructGetData($stSystemTime, 7), 2)

    ; DLLStructDelete()'s
    $stSystemTime = 0
    $stFileTime = 0
    $stLocalFileTime = 0

    Return $sDateTimeStr
EndFunc   ;==>_WinAPI_FileTimeConvert
; ##############################################################################################################
Edited by KaFu

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