Jump to content

_SelfDelete() - Delete the running executable.


guinness
 Share

Recommended Posts

Having used the _SelfDelete() function before, I knew it could be improved upon with adding more functionality to compensate for when an AutoIt error might occur.

The version I updated includes the ability to monitor when the process is closed and/or the timer is reached, therefore if an error was to occur with your program and the _SelfDelete() function was called before, it will still delete the executable even with an AutoIt error (due to bad coding of course!) This can't be said for the old version of _SelfDelete() as you'll never have chance to call the function! I also included the option to check either the process name or PID, depending on your preference. Thanks.

Function: Using a Batch script. Save as _SelfDelete.au3

#include-once
#include <FileConstants.au3>
#include <StringConstants.au3>

; #FUNCTION# ====================================================================================================================
; Name ..........: _SelfDelete
; Description ...: Delete the current executable after it's finished processing and/or the timer has been reached.
; Syntax ........: _SelfDelete([$iDelay = 5[, $fUsePID = False[, $fRemoveDir = False]]])
; Parameters ....: $iDelay              - [optional] An integer value for the delay to wait (in seconds) before stopping the process and deleting the executable.
;                                         If 0 is specified then the batch will wait indefinitely until the process no longer exits. Default is 5 (seconds).
;                  $fUsePID             - [optional] Use the process name (False) or PID (True). Default is False.
;                  $fRemoveDir          - [optional] Remove the script directory as well (True) or only the running executable (False). Default is False.
; Return values .: Success - Returns the PID of the batch file.
;                  Failure - Returns 0 & sets @error to non-zero
; Author ........: guinness
; Modified ......:
; Remarks .......: The idea for removing the directory came from: http://www.autoitscript.com/forum/topic/137287-delete-scriptdir/
; Example .......: Yes
; ===============================================================================================================================
Func _SelfDelete($iDelay = 5, $fUsePID = Default, $fRemoveDir = Default)
    If @Compiled = 0 Then
        Return SetError(1, 0, 0)
    EndIf

    Local $sTempFileName = @ScriptName
    $sTempFileName = StringLeft($sTempFileName, StringInStr($sTempFileName, '.', $STR_NOCASESENSEBASIC, -1) - 1)
    While FileExists(@TempDir & '\' & $sTempFileName & '.bat')
        $sTempFileName &= Chr(Random(65, 122, 1))
    WEnd
    $sTempFileName = @TempDir & '\' & $sTempFileName & '.bat'

    Local $sDelay = ''
    $iDelay = Int($iDelay)
    If $iDelay > 0 Then
        $sDelay = 'IF %TIMER% GTR ' & $iDelay & ' GOTO DELETE'
    EndIf

    Local $sRemoveDir = ''
    If $fRemoveDir Then
        $sRemoveDir = 'RD /S /Q "' & FileGetShortName(@ScriptDir) & '"' & @CRLF
    EndIf

    Local $sAppID = @ScriptName, $sImageName = 'IMAGENAME'
    If $fUsePID Then
        $sAppID = @AutoItPID
        $sImageName = 'PID'
    EndIf

    Local Const $iInternalDelay = 2, _
            $sScriptPath = FileGetShortName(@ScriptFullPath)
    Local Const $sData = 'SET TIMER=0' & @CRLF _
             & ':START' & @CRLF _
             & 'PING -n ' & $iInternalDelay & ' 127.0.0.1 > nul' & @CRLF _
             & $sDelay & @CRLF _
             & 'SET /A TIMER+=1' & @CRLF _
             & @CRLF _
             & 'TASKLIST /NH /FI "' & $sImageName & ' EQ ' & $sAppID & '" | FIND /I "' & $sAppID & '" >nul && GOTO START' & @CRLF _
             & 'GOTO DELETE' & @CRLF _
             & @CRLF _
             & ':DELETE' & @CRLF _
             & 'TASKKILL /F /FI "' & $sImageName & ' EQ ' & $sAppID & '"' & @CRLF _
             & 'DEL "' & $sScriptPath & '"' & @CRLF _
             & 'IF EXIST "' & $sScriptPath & '" GOTO DELETE' & @CRLF _
             & $sRemoveDir _
             & 'GOTO END' & @CRLF _
             & @CRLF _
             & ':END' & @CRLF _
             & 'DEL "' & $sTempFileName & '"'

    Local Const $hFileOpen = FileOpen($sTempFileName, $FO_OVERWRITE)
    If $hFileOpen = -1 Then
        Return SetError(2, 0, 0)
    EndIf
    FileWrite($hFileOpen, $sData)
    FileClose($hFileOpen)
    Return Run($sTempFileName, @TempDir, @SW_HIDE)
EndFunc   ;==>_SelfDelete
Function: Using a VBScript file. Save as _SelfDelete.au3

#include-once
#include <FileConstants.au3>
#include <StringConstants.au3>

; #FUNCTION# ====================================================================================================================
; Name ..........: _SelfDelete
; Description ...: Delete the current executable after it's finished processing and/or the timer has been reached.
; Syntax ........: _SelfDelete([$iDelay = 5[, $fUsePID = False[, $fRemoveDir = False]]])
; Parameters ....: $iDelay              - [optional] An integer value for the delay to wait (in seconds) before stopping the process and deleting the executable.
;                                         If 0 is specified then the script will wait indefinitely until the process no longer exits. Default is 5 (seconds).
;                  $fUsePID             - [optional] Use the process name (False) or PID (True). Default is False.
;                  $fRemoveDir          - [optional] Remove the script directory as well (True) or only the running executable (False). Default is False.
; Return values .: Success - Returns the PID of the batch file.
;                  Failure - Returns 0 & sets @error to non-zero
; Author ........: guinness
; Modified ......:
; Remarks .......: The idea for removing the directory came from: http://www.autoitscript.com/forum/topic/137287-delete-scriptdir/
; Example .......: Yes
; ===============================================================================================================================
Func _SelfDelete($iDelay = 5, $fUsePID = Default, $fRemoveDir = Default)
    If @Compiled = 0 Then
        Return SetError(1, 0, False)
    EndIf

    Local $sTempFileName = @ScriptName
    $sTempFileName = StringLeft($sTempFileName, StringInStr($sTempFileName, '.', $STR_NOCASESENSEBASIC, -1) - 1)
    While FileExists(@TempDir & '\' & $sTempFileName & '.bat')
        $sTempFileName &= Chr(Random(65, 122, 1))
    WEnd
    $sTempFileName = @TempDir & '\' & $sTempFileName & '.vbs'

    Local $sDelay = ''
    $iDelay = Int($iDelay)
    If $iDelay > 0 Then
        $sDelay = @TAB & 'iTimeOut = iTimeOut + 1' & @CRLF _
                 & @TAB & 'If iTimeOut > ' & $iDelay & ' Then' & @CRLF _
                 & @TAB & @TAB & 'For Each oProcess in oWMIQuery' & @CRLF _
                 & @TAB & @TAB & @TAB & 'oProcess.Terminate()' & @CRLF _
                 & @TAB & @TAB & 'Next' & @CRLF _
                 & @TAB & @TAB & 'iExit = 2' & @CRLF _
                 & @TAB & 'End If' & @CRLF
    EndIf

    Local $sRemoveDir = ''
    If $fRemoveDir Then
        $sRemoveDir = 'oFileSystem.DeleteFolder "' & @ScriptDir & '", True' & @CRLF
    EndIf

    Local $sAppID = @ScriptName, $sImageName = 'Name'
    If $fUsePID Then
        $sAppID = @AutoItPID
        $sImageName = 'ProcessId'
    EndIf

    Local Const $iInternalDelay = 10, _
            $sScriptPath = @ScriptFullPath
    Local Const $sData = 'Option Explicit' & @CRLF _
             & 'Dim iExit, iTimeOut, oFileSystem, oProcess, oWMIQuery, oWMIService, sComputer, sFilePath, sWMIQuery' & @CRLF _
             & @CRLF _
             & 'sFilePath = "' & $sScriptPath & '"' & @CRLF _
             & @CRLF _
             & 'iExit = 0' & @CRLF _
             & 'iTimeOut = 0' & @CRLF _
             & 'sComputer = "."' & @CRLF _
             & @CRLF _
             & 'Set oWMIService = GetObject("winmgmts:" _' & @CRLF _
             & @TAB & @TAB & '& "{impersonationLevel=impersonate}!\\" _' & @CRLF _
             & @TAB & @TAB & '& sComputer & "\root\cimv2")' & @CRLF _
             & @CRLF _
             & 'sWMIQuery = "Select * From Win32_Process Where ' & $sImageName & ' = ''' & $sAppID & '''"' & @CRLF _
             & @CRLF _
             & 'While (iExit = 0)' & @CRLF _
             & @TAB & 'Set oWMIQuery = oWMIService.ExecQuery(sWMIQuery)' & @CRLF _
             & @TAB & 'If oWMIQuery.Count = 0 Then' & @CRLF _
             & @TAB & @TAB & 'iExit = 1' & @CRLF _
             & @TAB & 'End If' & @CRLF _
             & @TAB & 'WScript.Sleep(1000)' & @CRLF _
             & $sDelay _
             & 'Wend' & @CRLF _
             & @CRLF _
             & 'WScript.Sleep(1000)' & @CRLF _
             & 'iExit = 0' & @CRLF _
             & 'iTimeOut = 0' & @CRLF _
             & 'Set oFileSystem = CreateObject("Scripting.FileSystemObject")' & @CRLF _
             & 'While (iExit = 0)' & @CRLF _
             & @TAB & 'iTimeOut = iTimeOut + 1' & @CRLF _
             & @TAB & 'If oFileSystem.FileExists(sFilePath) Then' & @CRLF _
             & @TAB & @TAB & 'oFileSystem.DeleteFile sFilePath, True' & @CRLF _
             & @TAB & 'End If' & @CRLF _
             & @TAB & 'If oFileSystem.FileExists(sFilePath) <> True Then' & @CRLF _
             & @TAB & @TAB & 'iExit = 1' & @CRLF _
             & @TAB & 'End If' & @CRLF _
             & @TAB & 'If iTimeOut > ' & $iInternalDelay & ' Then' & @CRLF _
             & @TAB & @TAB & 'iExit = 2' & @CRLF _
             & @TAB & 'End If' & @CRLF _
             & 'Wend' & @CRLF _
             & @CRLF _
             & $sRemoveDir _
             & 'oFileSystem.DeleteFile WScript.ScriptFullName, True' & @CRLF _

    Local Const $hFileOpen = FileOpen($sTempFileName, $FO_OVERWRITE)
    If $hFileOpen = -1 Then
        Return SetError(2, 0, False)
    EndIf
    FileWrite($hFileOpen, $sData)
    FileClose($hFileOpen)
    Return ShellExecute($sTempFileName, @TempDir, @TempDir, '', @SW_HIDE)
EndFunc   ;==>_SelfDelete
Example use of Function:

#include <MsgBoxConstants.au3>

#include '_SelfDelete.au3'

_SelfDelete(30, 0) ; Start the SelfDelete batch file with a 30 second timer and using the prcocess name rather than the PID.
If @error Then
    Exit MsgBox($MB_SYSTEMMODAL, '_SelfDelete()', 'The script must be a compiled exe to work correctly.') ; Display a warning if the script isn't compiled.
EndIf

While 1
    Sleep(100) ; Wait or manually close the application via the traymenu icon.
WEnd
WARNING: This will delete your executable if the function is called, so take the proper precautions and make sure you backup. Edited by guinness

UDF List:

 
_AdapterConnections() • _AlwaysRun() • _AppMon() • _AppMonEx() • _ArrayFilter/_ArrayReduce • _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 parsing • AutoIt Search • AutoIt3 Portable • AutoIt3WrapperToPragma • AutoItWinGetTitle()/AutoItWinSetTitle() • Coding • DirToHTML5 • FileInstallr • FileReadLastChars() • GeoIP database • GUI - Only Close Button • GUI Examples • GUICtrlDeleteImage() • GUICtrlGetBkColor() • GUICtrlGetStyle() • GUIEvents • GUIGetBkColor() • Int_Parse() & Int_TryParse() • IsISBN() • LockFile() • Mapping CtrlIDs • OOP in AutoIt • ParseHeadersToSciTE() • PasswordValid • PasteBin • Posts Per Day • PreExpand • Protect Globals • Queue() • Resource Update • ResourcesEx • SciTE Jump • Settings INI • SHELLHOOK • Shunting-Yard • Signature Creator • Stack() • Stopwatch() • StringAddLF()/StringStripLF() • StringEOLToCRLF() • VSCROLL • WM_COPYDATA • More Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

  • Moderators

@mesale0077 - You missed the point of what his does.

@guinness - If I'm reading your code right, it wouldn't just delete the exe, it looks like it would delete an .au3 if it was ran from SciTe.

Common sense plays a role in the basics of understanding AutoIt... If you're lacking in that, do us all a favor, and step away from the computer.

Link to comment
Share on other sites

Thanks, but this wasn't the point of my post.

UDF List:

 
_AdapterConnections() • _AlwaysRun() • _AppMon() • _AppMonEx() • _ArrayFilter/_ArrayReduce • _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 parsing • AutoIt Search • AutoIt3 Portable • AutoIt3WrapperToPragma • AutoItWinGetTitle()/AutoItWinSetTitle() • Coding • DirToHTML5 • FileInstallr • FileReadLastChars() • GeoIP database • GUI - Only Close Button • GUI Examples • GUICtrlDeleteImage() • GUICtrlGetBkColor() • GUICtrlGetStyle() • GUIEvents • GUIGetBkColor() • Int_Parse() & Int_TryParse() • IsISBN() • LockFile() • Mapping CtrlIDs • OOP in AutoIt • ParseHeadersToSciTE() • PasswordValid • PasteBin • Posts Per Day • PreExpand • Protect Globals • Queue() • Resource Update • ResourcesEx • SciTE Jump • Settings INI • SHELLHOOK • Shunting-Yard • Signature Creator • Stack() • Stopwatch() • StringAddLF()/StringStripLF() • StringEOLToCRLF() • VSCROLL • WM_COPYDATA • More Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

@guinness - If I'm reading your code right, it wouldn't just delete the exe, it looks like it would delete an .au3 if it was ran from SciTe.

I just updated with error checking by adding If @Compiled = 0 Then Return ... I simply forgot to add to the UDF, Thanks SmOke_N :mellow: Edited by guinness

UDF List:

 
_AdapterConnections() • _AlwaysRun() • _AppMon() • _AppMonEx() • _ArrayFilter/_ArrayReduce • _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 parsing • AutoIt Search • AutoIt3 Portable • AutoIt3WrapperToPragma • AutoItWinGetTitle()/AutoItWinSetTitle() • Coding • DirToHTML5 • FileInstallr • FileReadLastChars() • GeoIP database • GUI - Only Close Button • GUI Examples • GUICtrlDeleteImage() • GUICtrlGetBkColor() • GUICtrlGetStyle() • GUIEvents • GUIGetBkColor() • Int_Parse() & Int_TryParse() • IsISBN() • LockFile() • Mapping CtrlIDs • OOP in AutoIt • ParseHeadersToSciTE() • PasswordValid • PasteBin • Posts Per Day • PreExpand • Protect Globals • Queue() • Resource Update • ResourcesEx • SciTE Jump • Settings INI • SHELLHOOK • Shunting-Yard • Signature Creator • Stack() • Stopwatch() • StringAddLF()/StringStripLF() • StringEOLToCRLF() • VSCROLL • WM_COPYDATA • More Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

  • 4 weeks later...

For the sake of readability, try Opt('ExpandVarStrings', 1). Also you missed "" for the last DEL.

I actually didn't test it but applied those things.

; #AutoIt3Wrapper_Au3Check_Parameters=-d -w 1 -w 2 -w 3 -w 4 -w 5 -w 6
; #FUNCTION# =========================================================================================================
; Name...........: _SelfDelete()
; Description ...: Delete the current executable after it's finished processing and/or the timer has been reached.
; Syntax ........: _SelfDelete([$sFile = @ScriptName, [$iDelay = 5, [$iUsePID = 0]]])
; Parameters ....: $sFile - [optional] Filename of the batch file. [Default is the ScriptName.]
;                 $iDelay - [optional] An integer value for the delay to wait (in seconds) before stopping the process and deleting the executable.
;                                      If 0 is specified then the batch will wait indefinitely until the process no longer exits. [Default is 5 seconds.]
;                 $iUsePID - [optional] Use the process name or PID. [Default is 0 - 0 = use the process name or 1 = use the PID.]
; Requirement(s).: v3.3.2.0 or higher
; Return values .: Success - Returns the PID of the batch file.
;                 Failure - Returns 0 and sets @error to 1, this is because the executable isn't compiled.
; Author ........: guinness
; Example........; Yes
; Remarks........; none
;=====================================================================================================================
Func _SelfDelete($sFile = @ScriptName, $iDelay = 5, $iUsePID = 0)
    Local $hFileOpen, $iInternalDelay = 2, $sAppID = @ScriptName, $ExpandVarStrings, $sData, $sDelay = "", $sImageName = "IMAGENAME"
    #forceref $iInternalDelay, $sAppID, $sDelay, $sImageName

    If @Compiled = 0 Then
        Return SetError(1, 0, 0)
    EndIf
    $ExpandVarStrings = Opt('ExpandVarStrings', 1)
    If $iDelay <> 0 Then $sDelay = 'IF %TIMER% GTR $iDelay$ GOTO DELETE'

    If $iUsePID Then
        $sAppID = @AutoItPID
        $sImageName = "PID"
    EndIf
    $sFile = @TempDir & "\" & StringReplace($sFile, ".exe", "") & ".bat"

    $sData = StringFormat("" _
             & 'SET TIMER=0\r\n' _
             & @CRLF _
             & ':START\r\n' _
             & 'PING -n $iInternalDelay$ 127.0.0.1 > nul\r\n' _
             & $sDelay & ' \r\n' _
             & 'SET /A TIMER+=1\r\n' _
             & @CRLF _
             & 'TASKLIST /NH /FI "$sImageName$ EQ $sAppID$" | FIND /I "$sAppID$" >nul && GOTO START\r\n' _
             & 'GOTO DELETE\r\n' _
             & @CRLF _
             & ':DELETE\r\n' _
             & 'TASKKILL /F /FI "$sImageName$ EQ $sAppID$"\r\n' _
             & 'DEL "@ScriptFullPath@"\r\n' _
             & 'IF EXIST "@ScriptFullPath@" GOTO DELETE\r\n' _
             & 'GOTO END\r\n' _
             & @CRLF _
             & ':END\r\n' _
             & 'DEL "$sFile$"')
    $hFileOpen = FileOpen($sFile, 2)
    FileWrite($hFileOpen, $sData)
    FileClose($hFileOpen)
    Opt('ExpandVarStrings', $ExpandVarStrings)
    Return Run($sFile, @TempDir, @SW_HIDE)
EndFunc   ;==>_SelfDelete
Edited by FichteFoll
Link to comment
Share on other sites

I think you misunderstood the function and how it works with expanding the variable. I will try the other suggestion.

Edited by guinness

UDF List:

 
_AdapterConnections() • _AlwaysRun() • _AppMon() • _AppMonEx() • _ArrayFilter/_ArrayReduce • _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 parsing • AutoIt Search • AutoIt3 Portable • AutoIt3WrapperToPragma • AutoItWinGetTitle()/AutoItWinSetTitle() • Coding • DirToHTML5 • FileInstallr • FileReadLastChars() • GeoIP database • GUI - Only Close Button • GUI Examples • GUICtrlDeleteImage() • GUICtrlGetBkColor() • GUICtrlGetStyle() • GUIEvents • GUIGetBkColor() • Int_Parse() & Int_TryParse() • IsISBN() • LockFile() • Mapping CtrlIDs • OOP in AutoIt • ParseHeadersToSciTE() • PasswordValid • PasteBin • Posts Per Day • PreExpand • Protect Globals • Queue() • Resource Update • ResourcesEx • SciTE Jump • Settings INI • SHELLHOOK • Shunting-Yard • Signature Creator • Stack() • Stopwatch() • StringAddLF()/StringStripLF() • StringEOLToCRLF() • VSCROLL • WM_COPYDATA • More Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

I've updated the original post by adding quotation marks around the last DEL, thanks to FichteFoll for pointing out. About the code you posted it won't work for example you're using #forceref unnecessarily & 'TASKKILL /F /FI "$sImageName$ EQ $sAppID$" is encasing 'variables' incorrectly too.

UDF List:

 
_AdapterConnections() • _AlwaysRun() • _AppMon() • _AppMonEx() • _ArrayFilter/_ArrayReduce • _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 parsing • AutoIt Search • AutoIt3 Portable • AutoIt3WrapperToPragma • AutoItWinGetTitle()/AutoItWinSetTitle() • Coding • DirToHTML5 • FileInstallr • FileReadLastChars() • GeoIP database • GUI - Only Close Button • GUI Examples • GUICtrlDeleteImage() • GUICtrlGetBkColor() • GUICtrlGetStyle() • GUIEvents • GUIGetBkColor() • Int_Parse() & Int_TryParse() • IsISBN() • LockFile() • Mapping CtrlIDs • OOP in AutoIt • ParseHeadersToSciTE() • PasswordValid • PasteBin • Posts Per Day • PreExpand • Protect Globals • Queue() • Resource Update • ResourcesEx • SciTE Jump • Settings INI • SHELLHOOK • Shunting-Yard • Signature Creator • Stack() • Stopwatch() • StringAddLF()/StringStripLF() • StringEOLToCRLF() • VSCROLL • WM_COPYDATA • More Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

  • Moderators

Hi everybody

Try this this delete the running script, place this in the end of your script and compile it...

Run(@ComSpec & ' /c del ' & @ScriptName, @ScriptDir, @SW_HIDE) ; End of the script

1. Your code is flawed.

2. You've missed the point entirely.

Edited by SmOke_N
grammar

Common sense plays a role in the basics of understanding AutoIt... If you're lacking in that, do us all a favor, and step away from the computer.

Link to comment
Share on other sites

Thanks SmOke_N, I couldn't have put it better myself.

The main difference between the original _SelfDelete() is...

it will still delete the executable even with an AutoIt error (due to bad coding of course!).

UDF List:

 
_AdapterConnections() • _AlwaysRun() • _AppMon() • _AppMonEx() • _ArrayFilter/_ArrayReduce • _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 parsing • AutoIt Search • AutoIt3 Portable • AutoIt3WrapperToPragma • AutoItWinGetTitle()/AutoItWinSetTitle() • Coding • DirToHTML5 • FileInstallr • FileReadLastChars() • GeoIP database • GUI - Only Close Button • GUI Examples • GUICtrlDeleteImage() • GUICtrlGetBkColor() • GUICtrlGetStyle() • GUIEvents • GUIGetBkColor() • Int_Parse() & Int_TryParse() • IsISBN() • LockFile() • Mapping CtrlIDs • OOP in AutoIt • ParseHeadersToSciTE() • PasswordValid • PasteBin • Posts Per Day • PreExpand • Protect Globals • Queue() • Resource Update • ResourcesEx • SciTE Jump • Settings INI • SHELLHOOK • Shunting-Yard • Signature Creator • Stack() • Stopwatch() • StringAddLF()/StringStripLF() • StringEOLToCRLF() • VSCROLL • WM_COPYDATA • More Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

  • 4 months later...

I've updated the original post by adding quotation marks around the last DEL, thanks to FichteFoll for pointing out. About the code you posted it won't work for example you're using #forceref unnecessarily & 'TASKKILL /F /FI "$sImageName$ EQ $sAppID$" is encasing 'variables' incorrectly too.

I somehow found this thread again along your answer.

#forceref is used by Au3Check and especially for the "-w 5" param which stands for "local var declared but not used" and would complain when I did not use it there.

And "Opt('ExpandVarStrings', 1)" worked just as I expected. The only problem there was the $sDelay part, what you already mentioned. I don't know what it caused because the use of "%" would only be essential when using "Opt('ExpandEnvStrings', 1)", however I solved it by escaping them with "%%" like so:

; #AutoIt3Wrapper_Au3Check_Parameters=-d -w 3 -w 4 -w 5 -w 6
; #FUNCTION# =========================================================================================================
; Name...........: _SelfDelete()
; Description ...: Delete the current executable after it's finished processing and/or the timer has been reached.
; Syntax ........: _SelfDelete([$sFile = @ScriptName, [$iDelay = 5, [$iUsePID = 0]]])
; Parameters ....: $sFile - [optional] Filename of the batch file. [Default is the ScriptName.]
;                $iDelay - [optional] An integer value for the delay to wait (in seconds) before stopping the process and deleting the executable.
;                                     If 0 is specified then the batch will wait indefinitely until the process no longer exits. [Default is 5 seconds.]
;                $iUsePID - [optional] Use the process name or PID. [Default is 0 - 0 = use the process name or 1 = use the PID.]
; Requirement(s).: v3.3.2.0 or higher
; Return values .: Success - Returns the PID of the batch file.
;                Failure - Returns 0 and sets @error to 1, this is because the executable isn't compiled.
; Author ........: guinness
; Example........; Yes
; Remarks........; none
;=====================================================================================================================
Func _SelfDelete($sFile = @ScriptName, $iDelay = 5, $iUsePID = 0)
    Local $hFileOpen, $iInternalDelay = 2, $sAppID = @ScriptName, $ExpandVarStrings, $sData, $sDelay = "", $sImageName = "IMAGENAME"
    #forceref $iInternalDelay, $sAppID, $sDelay, $sImageName

    If @Compiled = 1 Then
        Return SetError(1, 0, 0)
    EndIf
    $ExpandVarStrings = Opt('ExpandVarStrings', 1)
    If $iDelay <> 0 Then $sDelay = 'IF %%TIMER%% GTR $iDelay$ GOTO DELETE'

    If $iUsePID Then
        $sAppID = @AutoItPID
        $sImageName = "PID"
    EndIf
    $sFile = @TempDir & "" & StringReplace($sFile, ".exe", "") & ".bat"

    $sData = StringFormat("" _
             & 'SET TIMER=0rn' _
             & @CRLF _
             & ':STARTrn' _
             & "PING -n $iInternalDelay$ 127.0.0.1 > nulrn" _
             & $sDelay & ' rn' _
             & 'SET /A TIMER+=1rn' _
             & @CRLF _
             & 'TASKLIST /NH /FI "$sImageName$ EQ $sAppID$" | FIND /I "$sAppID$" >nul && GOTO STARTrn' _
             & 'GOTO DELETErn' _
             & @CRLF _
             & ':DELETErn' _
             & 'TASKKILL /F /FI "$sImageName$ EQ $sAppID$"rn' _
             & 'DEL "@ScriptFullPath@"rn' _
             & 'IF EXIST "@ScriptFullPath@" GOTO DELETErn' _
             & 'GOTO ENDrn' _
             & @CRLF _
             & ':ENDrn' _
             & 'DEL "$sFile$"')
    $hFileOpen = FileOpen($sFile, 2)
    FileWrite($hFileOpen, $sData)
    FileClose($hFileOpen)
    Opt('ExpandVarStrings', $ExpandVarStrings)
    Return Run($sFile, @TempDir, @SW_HIDE)
EndFunc   ;==>_SelfDelete

This works, and it's far more readable than before.

Link to comment
Share on other sites

FichteFoll,

I hate to say this but your code has one major flaw, you're version will only work when the file isn't compiled, which is the total opposite to what it should be doing. Secondly I can't see any real benefit in StringFormat nor using ExpandVarStrings. But thanks for contributing.

UDF List:

 
_AdapterConnections() • _AlwaysRun() • _AppMon() • _AppMonEx() • _ArrayFilter/_ArrayReduce • _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 parsing • AutoIt Search • AutoIt3 Portable • AutoIt3WrapperToPragma • AutoItWinGetTitle()/AutoItWinSetTitle() • Coding • DirToHTML5 • FileInstallr • FileReadLastChars() • GeoIP database • GUI - Only Close Button • GUI Examples • GUICtrlDeleteImage() • GUICtrlGetBkColor() • GUICtrlGetStyle() • GUIEvents • GUIGetBkColor() • Int_Parse() & Int_TryParse() • IsISBN() • LockFile() • Mapping CtrlIDs • OOP in AutoIt • ParseHeadersToSciTE() • PasswordValid • PasteBin • Posts Per Day • PreExpand • Protect Globals • Queue() • Resource Update • ResourcesEx • SciTE Jump • Settings INI • SHELLHOOK • Shunting-Yard • Signature Creator • Stack() • Stopwatch() • StringAddLF()/StringStripLF() • StringEOLToCRLF() • VSCROLL • WM_COPYDATA • More Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

Do we have any working file, I have tried almost all of them but none of them is working or may be I don't know how to use this script. I was looking for such a script since very long, till now I am using cmd or bat file for deleting all the file including the one which is executing the commands.

Please guide me, if there is any such script.

Edited by niceguy75
Link to comment
Share on other sites

Did you try the example in the first post? If not then could you show what you did try along with your Windows OS and AutoIt version number. Thanks.

UDF List:

 
_AdapterConnections() • _AlwaysRun() • _AppMon() • _AppMonEx() • _ArrayFilter/_ArrayReduce • _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 parsing • AutoIt Search • AutoIt3 Portable • AutoIt3WrapperToPragma • AutoItWinGetTitle()/AutoItWinSetTitle() • Coding • DirToHTML5 • FileInstallr • FileReadLastChars() • GeoIP database • GUI - Only Close Button • GUI Examples • GUICtrlDeleteImage() • GUICtrlGetBkColor() • GUICtrlGetStyle() • GUIEvents • GUIGetBkColor() • Int_Parse() & Int_TryParse() • IsISBN() • LockFile() • Mapping CtrlIDs • OOP in AutoIt • ParseHeadersToSciTE() • PasswordValid • PasteBin • Posts Per Day • PreExpand • Protect Globals • Queue() • Resource Update • ResourcesEx • SciTE Jump • Settings INI • SHELLHOOK • Shunting-Yard • Signature Creator • Stack() • Stopwatch() • StringAddLF()/StringStripLF() • StringEOLToCRLF() • VSCROLL • WM_COPYDATA • More Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

How come nobody uses .vbs for this purpose?

No idea, but you're very welcome to post an example.

I've updated the original post with a script breaking change. _SelfDelete now only use 2 parameters compared to the previous 3. Please read the function header for more details.

Edited by guinness

UDF List:

 
_AdapterConnections() • _AlwaysRun() • _AppMon() • _AppMonEx() • _ArrayFilter/_ArrayReduce • _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 parsing • AutoIt Search • AutoIt3 Portable • AutoIt3WrapperToPragma • AutoItWinGetTitle()/AutoItWinSetTitle() • Coding • DirToHTML5 • FileInstallr • FileReadLastChars() • GeoIP database • GUI - Only Close Button • GUI Examples • GUICtrlDeleteImage() • GUICtrlGetBkColor() • GUICtrlGetStyle() • GUIEvents • GUIGetBkColor() • Int_Parse() & Int_TryParse() • IsISBN() • LockFile() • Mapping CtrlIDs • OOP in AutoIt • ParseHeadersToSciTE() • PasswordValid • PasteBin • Posts Per Day • PreExpand • Protect Globals • Queue() • Resource Update • ResourcesEx • SciTE Jump • Settings INI • SHELLHOOK • Shunting-Yard • Signature Creator • Stack() • Stopwatch() • StringAddLF()/StringStripLF() • StringEOLToCRLF() • VSCROLL • WM_COPYDATA • More Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

I decided to update the code with the suggestion provided in this thread >> Now _SelfDelete can have the option to delete the @ScriptDir too, though please backup before you do.

UDF List:

 
_AdapterConnections() • _AlwaysRun() • _AppMon() • _AppMonEx() • _ArrayFilter/_ArrayReduce • _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 parsing • AutoIt Search • AutoIt3 Portable • AutoIt3WrapperToPragma • AutoItWinGetTitle()/AutoItWinSetTitle() • Coding • DirToHTML5 • FileInstallr • FileReadLastChars() • GeoIP database • GUI - Only Close Button • GUI Examples • GUICtrlDeleteImage() • GUICtrlGetBkColor() • GUICtrlGetStyle() • GUIEvents • GUIGetBkColor() • Int_Parse() & Int_TryParse() • IsISBN() • LockFile() • Mapping CtrlIDs • OOP in AutoIt • ParseHeadersToSciTE() • PasswordValid • PasteBin • Posts Per Day • PreExpand • Protect Globals • Queue() • Resource Update • ResourcesEx • SciTE Jump • Settings INI • SHELLHOOK • Shunting-Yard • Signature Creator • Stack() • Stopwatch() • StringAddLF()/StringStripLF() • StringEOLToCRLF() • VSCROLL • WM_COPYDATA • More Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

How come nobody uses .vbs for this purpose?

Well having never used VBScript before (because AutoIt has been sufficient for my coding needs) I decided to spend the last day learning VBScript and having never created a .vbs file ever I came up with the following >>

Option Explicit
Dim iExit, iPID, iTimeOut, oFileSystem, oWMIService, sComputer, sFilePath, sWMIQuery

'~ PID to monitor when it's closed.
iPID = 2368
'~ Process filepath to delete.
sFilePath = "C:COMPILED_APP.exe"

iExit = 0
iTimeOut = 0
sComputer = "."

Set oWMIService = GetObject("winmgmts:" _
        & "{impersonationLevel=impersonate}!" _
        & sComputer & "rootcimv2")
sWMIQuery = "Select * From Win32_Process Where ProcessId = '" & iPID & "'"

While (iExit = 0)
    If oWMIService.ExecQuery(sWMIQuery).Count = 0 Then
        iExit = 1
    End If
    WScript.Sleep(500)
Wend

iExit = 0
Set oFileSystem = CreateObject("Scripting.FileSystemObject")
While (iExit = 0)
    iTimeOut = iTimeOut + 1
    If oFileSystem.FileExists(sFilePath) Then
        oFileSystem.DeleteFile sFilePath, True
    End If
    If oFileSystem.FileExists(sFilePath) <> True Then
        iExit = 1
    End If
    If iTimeOut > 10 Then
        iExit = 2
    End If
Wend

'~ oFileSystem.DeleteFolder oFileSystem.GetParentFolderName(sFilePath), True
oFileSystem.DeleteFile WScript.ScriptName, True
So I will create a new version of _SelfDelete in the next couple of days. Edited by guinness

UDF List:

 
_AdapterConnections() • _AlwaysRun() • _AppMon() • _AppMonEx() • _ArrayFilter/_ArrayReduce • _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 parsing • AutoIt Search • AutoIt3 Portable • AutoIt3WrapperToPragma • AutoItWinGetTitle()/AutoItWinSetTitle() • Coding • DirToHTML5 • FileInstallr • FileReadLastChars() • GeoIP database • GUI - Only Close Button • GUI Examples • GUICtrlDeleteImage() • GUICtrlGetBkColor() • GUICtrlGetStyle() • GUIEvents • GUIGetBkColor() • Int_Parse() & Int_TryParse() • IsISBN() • LockFile() • Mapping CtrlIDs • OOP in AutoIt • ParseHeadersToSciTE() • PasswordValid • PasteBin • Posts Per Day • PreExpand • Protect Globals • Queue() • Resource Update • ResourcesEx • SciTE Jump • Settings INI • SHELLHOOK • Shunting-Yard • Signature Creator • Stack() • Stopwatch() • StringAddLF()/StringStripLF() • StringEOLToCRLF() • VSCROLL • WM_COPYDATA • More Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

  • Jos locked this topic
Guest
This topic is now closed to further replies.
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...