Batch file that deletes itself and folder that contains it - windows

I'm trying to do the following but deleting the downloaded folder which contains the batch file fails:
NOTE: All exe's, apps, batch file etc. are contained in file.zip.
User downloads file.zip to any directory and unzips.
User runs an exe which is located in the unzipped folder.
This in turn runs two portable apps and some other things.
Once duties are performed, I remote in and run the same exe but this time I select an option that runs a batch file (located in unzipped folder) that starts a 30 second timer then is supposed to stop the apps and delete file.zip and the unzipped folder including the batch file itself.
Below is the batch file:
#echo off
mode con: cols=32 lines=7
color 4f
title
echo 30 Second Delay
echo Close window to abort
echo/
echo/
echo 0%% 100%%
SET /P var= <NUL
set count=0
:loop
PING -n 2 127.0.0.1 >NUL 2>&1
call :printline _
set /a count=count+1
if %count%==30 goto finish
goto loop
:printline
REM Print text passed to sub without a carriage return.
REM Sets line variable in case %1 intereferes with redirect
set line=%1
set /p var=%line%<NUL
exit /b
:finish
cls
color 0f
title Finished
mode con: cols=80 lines=25
echo Do NOT close this window!
echo/
echo Killing processes...
echo/
echo/
echo/
taskkill /t /f /im app1mainprocess.exe >nul
timeout /t 5 >nul
taskkill /t /f /im app2mainprocess.exe >nul
timeout /t 5 >nul
echo Do NOT close this window!
echo/
rem echo Restarting Windows Explorer...
rem timeout /t 10 >nul
rem taskkill /f /im explorer.exe >nul
rem start explorer.exe
echo Do NOT close this window!
echo/
echo Deleteing files and folders...
echo/
rem timeout /t 10 >nul
Set "Folder2Del=%~dp0"
cd ..
IF EXIST "file.zip" DEL "file.zip" /s /q >nul
rem echo %scrptDir%
echo Do NOT close this window!
echo/
echo Still working...
timeout /t 10 >nul
rd %Folder2Del% /s /q
(goto) 2>Nul & RD /S /Q "%Folder2Del%" & exit
The problem I encounter is that the folder never gets deleted. I realize my code is not correct but another reason is because one of the dll files in the unzipped folder is sometimes still in use by the dllhost.exe process.
I'm not sure if it is safe to add a line that kills the dllhost.exe process or not but my code still won't work because I have something wrong with how it deletes the batch file itself and the folder that contains it.
What lines do I need to edit and is it safe to kill dllhost.exe?

According to a link from dbenham
This does the trick:
#Echo off
Echo Ref: "http://www.dostips.com/forum/viewtopic.php?f=3&t=6491"
Set "Folder2Del=%~dp0"
cd "%~d0"
pause
(goto) 2>Nul & RD /S /Q "%Folder2Del%"
Take care the folder containing the batch is deleted
including any other files/folders without any further question!

Ok... I THINK I figured out how to do what I want by trying to delete the dll file, first, before trying to delete the entire directory. The code below looks for the problem dll and tries to delete it. If it still exists, it will try to delete the file every 30 seconds for up to 15 minutes. As soon as the dll gets deleted, the entire folder will also be deleted. If after 15 minutes the dll cannot be deleted, the remaining files in the folder will be deleted.
I still have a small issue. If I add code that kill/restarts Windows Explorer, the folder does not get deleted. Why and is there a workaround?
Below is the latest code:
#echo off
mode con: cols=32 lines=7
color 4f
title
echo 30 Second Delay
echo Close window to abort
echo/
echo/
echo 0%% 100%%
SET /P var= <NUL
set count=0
:loop
PING -n 2 127.0.0.1 >NUL 2>&1
call :printline _
set /a count=count+1
if %count%==30 goto finish
goto loop
:printline
REM Print text passed to sub without a carriage return.
REM Sets line variable in case %1 intereferes with redirect
set line=%1
set /p var=%line%<NUL
exit /b
:finish
cls
color 0f
title Uninstall
mode con: cols=80 lines=25
echo Do NOT close this window!
echo/
echo Killing processes...
tasklist /fi "imagename eq app1mainprocess.exe" |find ":" > nul
if errorlevel 1 taskkill /t /f /im "app1mainprocess.exe" > nul
tasklist /fi "imagename eq app2mainprocess.exe" |find ":" > nul
if errorlevel 1 taskkill /t /f /im "app2mainprocess.exe" > nul
timeout /t 5 >nul
rem echo Do NOT close this window!
rem echo/
rem echo Restarting Windows Explorer...
rem timeout /t 10 >nul
rem taskkill /f /im explorer.exe >nul
rem start explorer.exe
echo/
echo Deleteing file.zip if it exists...
timeout /t 5 >nul
Set "Folder2Del=%~dp0"
cd ..
IF EXIST "file.zip" DEL "file.zip" /s /q >nul
rem echo %Folder2Del%
rem Loops for 30 times in 30 second intervals (Total 15 minutes) to confirm deletion. Loop will exit after 30 loops and move on if dll cannot be deleted.
for /l %%i in (1,1,30) do (
del "%Folder2Del%name*.dll"
if not exist "%Folder2Del%name*.dll" goto Folder2Del
echo/
echo File locked! May take up to 15 minutes to delete.
echo Will stop trying 15 minutes after first attempt.
timeout /t 30 >nul
)
:Folder2Del
echo/
echo Attempting to delete the Connector folder and it's contents...
timeout /t 5 >nul
rd "%~dp0" /s /q & exit

Related

How to stop a cmd file from showing Network error messages

Error Message I want to remove:
I get this error when I run a code that runs a shortcut that's shared over network.
How can I stop cmd script from showing Network Errors like these, even if I know there is an error?
#echo off
echo.
echo 1. Add
echo 2. Remove
echo.
set /p var= Type option number here -
if %var%==1 (goto :add)
if %var%==2 (goto :remove)
if else (goto :EOF)
:add
reg add HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\NetworkProvider\ /v RestoreConnection /d 0
echo.
echo SUCESSFULLY ADDED!
timeout /t 2 /nobreak >nul &exit
:remove
reg delete HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\NetworkProvider\ /v RestoreConnection
echo.
echo SUCESSFULLY REMOVED!
timeout /t 2 /nobreak >nul &exit
This .bat script could come handy btw. Atleast it's easier than changing the registry manually. You can add and delete the value any time you want, so its convenient. Save this as a (.bat) file and use it...
Thanks #FiddlingAway for giving reference for the script : )

Get out of loop if more than one minute Windows Batch file

I am trying to delete a folder on Windows server if a certain condition is met. If it is not met, then a wait for 10 seconds and loop around, check for the condition again. I also need to make sure that I am not in the loop forever. (Check if I am in the loop for more than 60 seconds, then get out of the loop). The batch file looks something like this:
C:\postgresql\uninstall-postgresql.exe --mode unattended
set TIMESTAMP1=%TIME%
:deleteFolder
tasklist /V |findstr /i "_uninstall*" >nul
if %errorlevel% == 0 (timeout /T /10 >nul
set TIMESTAMP2=%TIME%
**REM I want to make sure that we get out of this loop if the diff b/w TIMESTAMP2
AND TIMESTAMP1 IS MORE THEN 60 SECONDS**
goto deleteFolder
) ELSE (
if exists C:\postgresql RD /Q /S C:\postgresql)
Command 1
Command 2
Command 3
So, I am trying to uninstall Postgresql from a windows server, making sure that the uninstall is complete by checking the tasklist and then delete the basedir (C:\postgresql). If the uninstall process is still running, then wait for 10 seconds and check the tasklist again. I just want to make sure that I am not stuck in the loop forever.
Thanks in advance
Using timestamps and calculating time difference:
#echo off
setlocal EnableDelayedExpansion
C:\postgresql\uninstall-postgresql.exe --mode unattended
set "startTime=%time: =0%"
set "endTime="
:deleteFolder
tasklist /V |findstr /i "_uninstall*" >nul
if %errorlevel% == 0 (
goto waitAndDeleteFolder
) else (
goto cleanup
)
:waitAndDeleteFolder
timeout /T 10
set "endTime=%time: =0%"
set "end=!endTime:%time:~8,1%=%%100)*100+1!" & set "start=!startTime:%time:~8,1%=%%100)*100+1!"
set /A "elap=((((10!end:%time:~2,1%=%%100)*60+1!%%100)-((((10!start:%time:~2,1%=%%100)*60+1!%%100), elap-=(elap>>31)*24*60*60*100"
if !elap! gtr 6000 goto done
goto deleteFolder
:cleanup
if exist "C:\postgresql" RD /Q /S "C:\postgresql"
goto done
:done
The simpler method would be to utitlise a count to break the loop
#Echo off & Set Count=0
C:\postgresql\uninstall-postgresql.exe --mode unattended
:deleteFolder
If "%Count%"=="6" Goto :Failed
tasklist /V |%__AppDir_%findstr.exe /lic:"_uninstall" >nul 2> Nul && (Timeout /T 10 /Nobreak > Nul & <Nul Set /P "=." & Set /A "count+=1" & Goto :deleteFolder) || Goto :Post
:Post
if exist C:\postgresql (
RD /Q /S C:\postgresql && Echo/Task Completed
) Else Echo/C:\postgresql Absent
Goto :Eof
:Failed
Echo/Task failed to complete in the allocated time
Goto :Eof
I would however suggest a more robust approach on your part to identifying the task

Windows batch file looping Wait animation during processing command

I have created the following batch file that makes Wait "| / -- \" animation. I want to use it during processing mysql restore database command mysql -u %DBuser% -p %DB% < "%thefile%" where thefile is the sql dump file path
#Echo OFF
setlocal EnableDelayedExpansion
for /f %%a in ('copy /Z "%~f0" nul') do set "CR=%%a"
SET p=-1
set num=1
set "st[1]=| "
set "st[2]=/ "
set "st[3]=--"
set "st[4]=\ "
if /i %p% lss 0 (
set p=2
call :LOOP
call :DoSomeThing
)
:LOOP
if /i %num% lss 4 (
set /a num=num+1
) else (
set num=1
)
<nul set /P "=Wait !st[%num%]!!CR!"
TIMEOUT /T 1 >NUL
GOTO :LOOP
:DoSomeThing
TIMEOUT /T 10 >NUL
echo Doing...
Here, :DoSomeThing is for testing purposes and It should be replaced or include the mysql command. I get the problem that :LOOP works for ever and there is no call to :DoSomeThing
I tried to call :DoSomeThing before call :LOOP but the LOOP started after DoSomeThing is finished so it becomes useless! Is there any way to make the DoSomeThing or the MySQL command works in the background while the animation wait loop works too?
EDIT: Some explanations added
In order to fulfill your request it is necessary to execute two threads simultanously, so one thread execute the mysql command and the other thread execute the looping wait animation. Both threads can be synchronized using a flag file that is created before mysql execution starts and is deleted after it ends, so the wait animation loops until the flag file is deleted.
The way to create a new thread is via start command, that may run a second Batch file that execute the mysql command and delete the flag file. However, in order to keep all the code in the same place, the start command may run the same Batch file (represented by "%~F0" in the code below). The key that allows this trick to work is a special parameter that indicate if the Batch file was re-executed from inside itself, so in this case the code just goto the section that execute the mysql command and delete the flag file.
#Echo OFF
rem If the Batch file was re-executed with the special parameter (second thread)
rem go to the section that execute the mysql command
if "%~1" equ ":DoSomething" goto %1
setlocal EnableDelayedExpansion
for /f %%a in ('copy /Z "%~f0" nul') do set "CR=%%a"
set num=0
set "st[0]=| "
set "st[1]=/ "
set "st[2]=--"
set "st[3]=\ "
rem Do here anything you want before the mysql command...
echo Doing something for 10 seconds...
rem Create the flag file
echo X > DoingSomething
rem Re-start this Batch file with the special parameter
start "" /B "%~F0" :DoSomething
rem Simultaneously execute the waiting animation
call :LOOP
rem Do here anything you want after the mysql command...
rem ... and terminate
goto :EOF
:LOOP
set /a num=(num+1) %% 4
<nul set /P "=Wait !st[%num%]!!CR!"
TIMEOUT /T 1 >NUL
IF EXIST DoingSomething GOTO :LOOP
echo Ending loop
goto :EOF
:DoSomeThing
rem Place here the mysql command
TIMEOUT /T 10 >NUL
rem Delete the flag file
del DoingSomething
rem And terminate the second thread
goto :EOF

Batch File Skipping If Statement

It seems that whenever I run my Batch file, everything will run, and it'll go into checkfiles, but it doesn't operate the if statement. Nothing is returned, it just skips right over unto the last part of the code.
:file_check
if exist "%psychedelia%\nhc.exe" (goto file_exists) else (timeout /t 1 /nobreak > output)
goto file_check
:file_exists
copy /Y "%~dp0version.txt" "%psychedelia%"
:checkfiles
echo in checkfiles
if exist "%psychedelia%\wa.exe" if exist "%psychedelia%\readme.txt" if exist "%psychedelia%\HD.BLB" if exist "%psychedelia%\smackw32.dll" if exist "%psychedelia%\setup95.exe" if exist "%psychedelia%\WAVistaWin7.exe" (
echo MSGBOX "Thank you for installing the Neverhood. You may now go to your desktop and click on the Orpheus shortcut to play!" > %temp%\TEMPxmessage.vbs
call %temp%\TEMPxmessage.vbs
del %temp%\TEMPxmessage.vbs /f /q
rename "%psychedelia%\nhc.exe" wa.exe
timeout /t 1 /nobreak > output
taskkill.exe /F /IM setup95.exe /T
) else (
echo nonexistent
pause
timeout /t 1 /nobreak > output
goto checkfiles
)
All help is greatly appreciated.
Only the last if exist on that line has parentheses, so the else only applies to that last one. If any of the first ones evaluate to false, it will just skip the whole thing.
Try:
...
echo in checkfiles
for %%f in (wa.exe
readme.txt
HD.BLB
smackw32.dll
setup95.exe
WAVistaWin7.exe
) do if not exist "%psychedelia%\%%f" (
echo %%f nonexistent
pause
timeout /t 1 /nobreak > output
goto checkfiles
)
:: all required files found
echo MSGBOX "Thank you for installing the Neverhood. You may now go to your desktop and click on the Orpheus shortcut to play!" > %temp%\TEMPxmessage.vbs
call %temp%\TEMPxmessage.vbs
del %temp%\TEMPxmessage.vbs /f /q
rename "%psychedelia%\nhc.exe" wa.exe
timeout /t 1 /nobreak > output
taskkill.exe /F /IM setup95.exe /T
It might be easier to maintain.
In fact, you could even write
set requiredfiles=wa.exe readme.txt HD.BLB smackw32.dll setup95.exe WAVistaWin7.exe
for %%f in (%requiredfiles%) do if not exist "%psychedelia%\%%f" (
...
which would be even easier.

Resume batch script after computer restart

I have a bunch of old machines running Windows 2000 Pro and IE 5.0 which I want to upgrade to IE 6 with Silverlight. I downloaded the IE6 and Silverlight installers from Microsoft's web sites and fortunately they both have command line options to allow them to run in "silent mode".
I put the two commands in a DOS batch script and ran it, but the IE6 installer requires makes an automatic computer restart so the question is how to resume the script and run the 2nd command (install Silverlight).
My batch file is very simple right now:
ie6setup.exe /Q
silverlight.exe /q
From what I know, batch files can't resume execution after restarting the computer. Is there a way to make them do that? of is there another way to accomplish what I need.
Thank you
Based on Tim's post which, when tested, appended "two" to the batch file resulting in a failure to find the batch label "onetwo", so amended to read & write the "current" variable from a seperate text file, leaving the batch file untouched;
#echo off
call :Resume
goto %current%
goto :eof
:one
::Add script to Run key
reg add HKCU\Software\Microsoft\Windows\CurrentVersion\Run /v %~n0 /d %~dpnx0 /f
echo two >%~dp0current.txt
echo -- Section one --
pause
shutdown -r -t 0
goto :eof
:two
echo three >%~dp0current.txt
echo -- Section two --
pause
shutdown -r -t 0
goto :eof
:three
::Remove script from Run key
reg delete HKCU\Software\Microsoft\Windows\CurrentVersion\Run /v %~n0 /f
del %~dp0current.txt
echo -- Section three --
pause
goto :eof
:resume
if exist %~dp0current.txt (
set /p current=<%~dp0current.txt
) else (
set current=one
)
You could put the second command in a exclusive batch file, and add an entry to regedit to execute this batch file automatically upon Windows' start, making silverlight be executed after the computer restarts.
Have you heard of msconfig? On some systems the regedit PATH you are looking for is:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
But you may want to check that. If you want to make a batch file to write that key on the registry, you probably should take a look at this tutorial.
If you do the IE6 installation with the command ie6setup.exe /q /r:n then it won't reboot automatically (see this page for details). Then theoretically you could install SilverLight immediately, and then reboot afterwards; but there is a chance that the SL install will refuse due to the need of a reboot, but it won't hurt to try it...
I know its a bit old but this works amazingly:
#echo off
call :Resume
goto %current%
goto :eof
:one
echo two >>myfile.cmd
::REBOOT HERE
goto :eof
:two
echo resumed here
goto :eof
:resume
rem THIS PART SHOULD BE AT THE BOTTOM OF THE FILE
set current=one
#echo off
set "_RunOnce=HKCU\Software\Microsoft\Windows\CurrentVersion\RunOnce"
rem./ :: if no argument was passed, this line will be ignored, but if so, it will be executed here == ^> & %~1
:1st_command
ie6Setup.exe /Q
shutdown -r -t 0 | reg add "%_RunOnce%" /v "%~n0" /d "\"%~f0\" \"goto :2nd_command\"" /f & goto :eof
:2nd_command
SilverLight.exe /Q
timeout -1 | shutdown -r -t 0 | reg add "%_RunOnce%" /v "%~n0" /d "\"%~f0\" \"goto :3rd_command\"" /f & goto :eof
:3rd_command
Skype-8.92.0.401.exe /VerySilent /NoRestart /SuppressMsgBoxes /DL=1 & goto :eof
It is possible to do it without creating or manipulating readings in additional files, just writing and reading in the key and using arguments passed in the execution to control the command necessary for the relevant execution, using goto command as an argument %1
#echo off
set "_RunOnce=HKCU\Software\Microsoft\Windows\CurrentVersion\RunOnce"
rem./ if no argument was passed, below will be ignored, but if so, it will be executed here == ^> & %~1
:1st_command
mode con cols=50 lines=1 | title starting %~1
start "google" /wait "c:\program files (x86)\Google\Chrome\Application\chrome.exe" "stackoverflow.com" /new-tab
timeout -1 | shutdown -r -t 0 | reg add "%_RunOnce%" /v "%~n0" /d "\"%~f0\" \"goto :2nd_command\"" /f & goto :eof
:2nd_command
mode con cols=50 lines=1 | title starting %~1
start "google" /wait "c:\program files (x86)\Google\Chrome\Application\chrome.exe" "meta.stackexchange.com" /new-tab
timeout -1 | shutdown -r -t 0 | reg add "%_RunOnce%" /v "%~n0" /d "\"%~f0\" \"goto :3rd_command\"" /f & goto :eof
:3rd_command
mode con cols=50 lines=1 | title %~1
start "google" /wait "c:\program files (x86)\Google\Chrome\Application\chrome.exe" "www.amazon.com" /new-tab
goto :eof

Resources