Self executing delete files - windows

How would I create a self executing batch file to delete files in a specific folder.
Scenario: I have a folder on a server where all the scannered documents go to once they have been scanned. They want a the scanned documents to be deleted after 1 day. Can a batch file be created to do that everyday?

You can use the built in task scheduler - this can call a batch file, or just about anything.
(I am assuming Windows, since you mention batch files).

This is quite a well known method, and was documented in MSDN some time ago. This technique works on both Windows 95 and Windows NT. It works because MS-DOS batch files are able to delete themselves. To test this technique, create a small batch file containing the single command:
del %0.bat
The batch file, when run, deletes itself and issues an error "The batch file cannot be found". This error is just a simple message, so it can be safely ignored. By itself this isn't too useful, but when modified to delete our executable it solves our problem, albeit in a rather forceful manner. Our executable will create a batch file (called C:\DelUs.bat) with the following content:
:Repeat
del "C:\MYDIR\MYPROG.EXE"
if exist "MYPROG.EXE" goto Repeat
rmdir "C:\MYDIR"
del "\DelUS.bat"
This batch file repeatedly attempts to delete the specified file, and will run continuously consuming CPU until it succeeds. When the execuable has been deleted, the batch file then deletes itself.
The executable needs to spawn off the batch file using CreateProcess, and then should exit immediately. It would be a good idea to give the batch file's thread of execution a low priority so that it doesn't get much execution time until the original executable has terminated.
Read the entire article at http://www.catch22.net/tuts/self-deleting-executables that contains the full code to this technique.

Related

Safely modify batch file while running

I'm implementing a batch file similar to the Gradle wrapper. The idea is that it will download the main application and run it, without the user having to download and install the application itself.
This is all working fine, and now I'm implementing updating the application. This involves replacing the batch file with a new version of the batch file (which has a new download URL in it, in addition to any changes to the batch file itself).
However, when my application replaces the batch file, this leads to weird results (as discussed in https://stackoverflow.com/a/31257641/1668119 and other answers in that question). Is there a safe way to replace a batch file while it is running that doesn't result in new or removed lines causing issues?
Based on Mofi's comment and the answer they linked to, I'm using something like this:
setlocal EnableDelayedExpansion
my-application && exit 0 || exit !ERRORLEVEL!
The batch file executor seems to read the file one line at the time, so always exiting on that line means it will never try to read anything more from the batch file and so it doesn't matter if the batch file has been modified.
setlocal EnabledDelayedExpansion is important as otherwise ERRORLEVEL is evaluated before the application is run and so the script always returns 0 even if the application fails.

File Move Scheduled Tasks not running bat file

I know this question might have been asked in other ways, but all the things I have read and tried had not yet fixed my problem, so I am hoping to get some help here with context to my issue.
The problem:
I need to move files from a local drive to a network drive (the network drive is a SharePoint mapped library) on my server in Windows Azure (don't think the azure part matters, but it provides context).
My thought was to schedule a task that will run a bat file to move the files I need moved and do so frequently (every 5 to 10 minutes). The batch file I have created does what I need it to when I manually run the batch file but not when the task runs it.
Here is the batch file:
echo Write log file > LogStart.txt
C:\Windows\System32\robocopy.exe "\\PCICSWKS001\D$\ToBeMoved" "V:" /s /e /MOV /r:0 /W:0
echo Write log file > LogEnd.txt
You can see that it writes a log file before and after running robocopy.exe.
When the task runs it does write both of these log files so I know that the batch file is at least running.
You can also see that I have tried using the UNC path for the drive in the source, that is because I was reading that the task scheduler might not be able to pick up properly on the drive letters. When I put the machine name in for the destination and run the batch file myself or with the scheduler it errors.
Here is the action taken by the task:
Here is the task general tab
Any assistance would be much appreciated.
I had that same error with Robocopy after a few times of running it:
ERROR 3 (0x00000003) Getting File System Type of Destination
I think it has to do with how robocopy scans the destination when it has a fair amount of files on it. It worked fine when I started the copy job and the Azure destination was empty.
Anyway, I think you should try to use the AzCopy command as that should be less error prone and faster since it was designed for this kind of thing. It's command line switches are similar to robocopy so it should feel pretty familiar.

How can I test for errors in a .bat file that calls an .exe?

I'm writing a .bat file that calls a .exe that processes a bunch of documents. I am writing it to test the .exe's performance. Currently, the .bat file runs a for loop to run the .exe on every file in the folder. Sometimes the .exe will run into errors and will not be able to finish running due to incompatibility between the document and the .exe (still working on perfecting the .exe). How can I tell my .bat file to mark the bad files as errors and continue processing the rest of the files?
Edit: I don't want to terminate the batch file; I'd like to terminate the .exe for that specific file, and then continue with the for loop.

Build output from Visual Studio 2010 external tools in output window

I run a batch file as an external tool (by adding it in Tools->External tools) in VS2010 (I've checked the "Use Output Window" option). This batch file performs compilation as in VS command prompt. The project that I'm working on has makefiles for various folders, so I use the mk command to build.
In the batch file, I set up the VS environment and then run the following commands:
cd $directoryWhichContainsFileToBuild
mk
cd main //This directory contains the executable that is to be built
mk
I see the output of the first mk in the Output window but after that it just hangs. I also tried to use an echo after the first mk but even that doesn't get printed in the output window (the ones before it can be seen).
Somewhere I read that there is an issue with VS 2010 output window where it hangs after showing some output, although I couldn't really be sure that that is what's the issue here.
Do I need to enable some other VS setting? Has anybody else encountered this issue?
Thanks.
Update: I unchecked the "Use Output Window" and "Close on exit" option, and I see an extra statement: "Press any key to continue". On doing that however, their is no further processing of the batch file.
Update2: Got it to work by prefixing mk with "call".
Thanks all who tried.
It is always good in batch files to specify executables with full path and file extension instead of just the file name. This avoids often lots of problems.
Here was just mk used instead of mk.bat. Therefore on every compile the command line processor cmd.exe searches for mk.* and then checks if any of the found files have an extension listed in environment variable PATHEXT. The order of file extensions separated by a semicolon in PATHEXT defines the order of execution in case of a directory contains multiple mk.* files.
If a command being specified in a batch file not being an internal command of cmd.exe without path, command line processor searches first for a file with given name in current working directory. This is often one more cause of error. What is the current working directory on execution of the batch file?
Next if no file to execute can be found in current working directory, the command line processor searches in all folders being listed in environment variable PATH separated by semicolons.
So specifying in batch files edited only rarely an external application or another batch file with full path, file name and file extension, in double quotes if necessary because of 1 or more spaces in path or file name, helps command line processor to more quickly execute that application or batch file and avoids problems because of executable not found (unknown command).
Sure, when typing commands in a command prompt window, nobody wants to enter the executables with full path, name and extension. But for batch files it is always good to be not lazy and type files to be executed with full path and extension.
TripeHound has given already the explanation why the observed behavior occurred here.
If a batch file is executed from another batch file without using command call, the command line processor continues batch execution in the other batch file and does never come back. In a C/C++ program this is like using goto with the difference that parameters can be passed to the batch file containing the further commands to be executed next.
But running from within a batch file another batch file with call results in continuation of execution below the line calling the other batch file once the other batch file reaches end, except command exit is used in the called batch file without parameter /B.
So the solution here is using:
cd /D "Directory\Which\Contains\File\To\Build"
call "Path\Containing\Batch\File\To\Build\mk.bat"
rem With mk.bat not changing current working directory change working
rem directory to the directory containing the executable to be built.
cd main
call "Path\Containing\Batch\File\To\Build\mk.bat"
BTW: exit exits command processor, exit /B exits just current batch file. I'll give you three guesses why the parameter is B and not a different letter. Yes, B is the first letter of batch.
Writing as a separate answer instead of an update in the question itself as many readers see the header and skim to the answer: got it to work by prefixing mk with "call". (#TripleHound has also posted the conceptual reason for it in the comment above.)

CMD: Bat to Exe Converter - Temp directory problem

i am using 'Bat to Exe Converter' to convert my batch files to exe format.
Now, i am running into some problems.
Whenever i convert something, and i set 'Working Directory' to 'Current Directory', and i start my exe in echo on mode, this is what i end up with to check if there is a specific file in the directory of my exe:
the actual command: if not exist "%~dp0\file.txt" goto :nofile
output: if not exist "C:\Users\MyUser\AppData\Local\Temp\4CBC\\file.txt" goto :nofile
Can anyone help me with this? I don't want it in the temp directory, i want it to be in the directory of my exe.
Thanks.
Without having Bat to Exe changed by the author, I think you have two options:
Remove the need for accessing %~dp0
Perhaps you can merge file.txt with the include option of Bat to Exe into the EXE file. If so, "file.txt" will automatically be unpacked in the current directory when running your compiled exe, and you can it access by %CD%\file.txt.
Get %~dp0 from outside and pass it to the exe as a command line parameter.
This can be done by a simple starter bat file that resides in the same directory as your compiled main batch file. This script schould contain the line
YourCompiled.Exe %~dp0% %%*
Your compiled exe then gets its directory from %1. So you cannot pack everything into one exe, but the main portion of it, perhaps that is sufficient for you.
Well, apparently your batch to exe converter simply packs the batch file and extracts it to a temporary directory prior to execution. Very simplistic, hard to get wrong (compared to actually understand the batch file) but it introduces errors such as the one you're describing.
Your best bet is probably to use another batch to exe converter; some of them are actually a little more sophisticated.
Generally, this is not a good idea. firstly, its prone to errors and instability of the converter on different cmd features. secondly, a determined hacker can still decode what you are doing with the batch. My suggestion, if you are so afraid of people looking into your batch,
1) let only the people who are authorized to use your batch to use it
2) give them the correct permissions.
OR, don't use batch at all
1) create a central interface such as a web interface, where all tasks to be done goes through that interface, like using an ATM machine where only buttons are allowed and all the available user options can be done by pushing buttons...etc..
2) authenticate your users through a central authentication system, eg Active Directory, or LDAP or a database.
This is an 2.5 yr old subject but there is an answer to this so I'm posting for anyone else that happens to find this in a search.
B2EC written by Fatih Kodak, has an option to "Submit current directory".
When this is used, you can reference %1 in your batch file to get the path of the EXE that was executed (instead of the path of the extracted BAT that is really being run).
Hovering over that option in the UI shows "Submit the current working directory as the last parameter". The "last parameter" in my use has always been %1 but you can test your code to be sure.
The latest version, 2.1.4 at time of writing, of Bat to Exe by Fatih Kodak creates an Environmental Variable at runtime that can be substituted in place of %~dp0 to reference the Exe's path. Therefore, you can simply replace %-dp0 with %b2eprogrampathname% in the original batch file.
You can use external folders with f2ko's batch to exe converter. Having
a separate folder for subroutines can neaten up a project folder.
To call mysubroutine that is located in mysubroutinesfolder\mysubroutine,
...
pushd mysubroutinesfolder
call mysubroutine
popd
...
The call can be made a one liner:
call xqt mysubroutine
where xqt.cmd is a program that does the call for you:
pushd mysubroutinesfolder
call %*
popd
exit /b
(the %* means "all of the arguments").
In this way your batch programs run as batch, and UNMODIFIED they will
compile with the bat to exe converter, creating a completely folder independent executable. Select "temporary directory",
and include all of the subroutines/executables in your mysubroutines folder
by "selecting them all" with your cursor as usual, then hit "copy".
Be sure to include the xqt.cmd program too; place it "outside" of your mysubroutines folder. Make sure that is is accessible by your main program. Remember to select x64 if you
are runnning on a x64 machine, or the executable will not find SYSTEM32
files. You can find f2k0's batch to exe converter at:
http://www.f2ko.de/programs.php?pid=b2e
Try this development environment for batch scripts, Batch Compiler . It has everything you need to develop a batch program.And compile into stable stand alone executable (Exe).
Friendly user interface.
Debugger, Check your code for syntax errors.
Powerful, versatile compiler.
Allows mouse input in batch files.
Use Windows Common Dialog Boxes.(BrowseFiles,BrowseFolders)
Draw graphics in batch files.
Reverse engineering proof encryption of source code.
Include Company name, Copyright info and Version info.
Make invisible(silent) executables.
Executables with administrator privileges.
Run & debug your script while editing.
Embed resources with executable.(music,images,files)
Advance Commands (BrowseFiles,LaunchSilent,MouseCMD)
Stand-alone executables.No dependencies needed.
Executables are woking on almost all windows operating systems.(98 to 10)
Quick download : http://bc.gotek.info/files/BatchCompiler159.zip
Cheers!
%cd% will give you the current directory:
if not exist "%CD%\file.txt" goto :nofile
Use %CD% instead of %~dp0.
EDIT:
B2EC is not a real converter. Creation location of equipped .cmd file was chosen to be %TEMP% and this is a good choice. Application just lacks 3rd option for working directory of the script - .exe file directory. I advise you to mail the author about adding this one.
Different paths for .exe and created .cmd lead to information loss, i.e. we are unable to know .exe directory and current directory at the same time without providing additional information to the script (e.g. using environment variable or passing it as first/last argument to the script). This script would need to handle it and we would end writing cmd scripts tailored for this converter, which is bad.
%~dp0 - script directory (%TEMP%/.../) - practically useless
%cd% - working directory (as set up in the converter) - currently there are only 2 options: current directory (working directory of .exe) and temporary directory (actually equal to %~dp0, but without trailing backslash)
I think it can be solved by patching cmd.exe instance in memory to change the script path, but that's B2EC developer's duty.
Side note: Normal executable files can be easily executed with specified 0th argument by providing appriopriate lpApplicationName and lpCommandLine to CreateProcess function. Command files are executed via cmd.exe, so 0th argument cannot be set this way.

Resources