Wednesday, November 5, 2008

Going into stealth mode

We took a troubleshooting lab today, and I was able instantly to figure out what was wrong because the script we were told to run to "break" our computers showed it's output in the DOS box. Because the script had a significant pause during execution, it showed exactly what it was doing, so rectifying that was very simple. Due to this, I wondered if it would be possible to hide the execution of a script. I did a little Googling and this is what I discovered.

Failed Attempt:

I at first wanted to completely hide the DOS box from coming up at all, however from what I read this is simply not possible with a batch file. Then I came across a solution that suggested using the redirect symbol after the command to pipe the output to NULL. This method does show a DOS box, but hides the output. So, say you wanted to delete a file called trash.txt with a batch file, without revealing in the DOS box that you were doing so. In this case your batch file would contain:

@echo off ; prevents the command itself from being displayed
del trash.txt >NULL

and this would execute the command while directing the output to nowhere. However, when I tried this method, it merely made a file called NULL with the output in it. It did hide the output in the DOS box, but created a useless file, which was not my intention. Closer, but no cake.

The Real Deal:

I modified my Google search to be "redirecting output to null" or something along those lines, and quickly came across the true answer. You have to redirect the output to NUL with one L, not NULL with two. After testing this method, I found that it did indeed work. So, in the example above, the batch file would contain this:

@echo off ; prevents the command itself from being displayed
del trash.txt >NUL

This would send the output to nowhere, while not affecting the execution of the command. I like this solution because it is simple and easy. A DOS box will still flash up momentarily, but it will open and close much faster than it would otherwise, and no text will be displayed.

Be warned that I at least would not want a normal program to be flashing empty DOS boxes during execution - that would make me very suspicious. A batch file setting up a debugging test is a different matter, and is in honesty the only real use I can see for this. If you want to suppress a spam of text in a window by using this, I would suggest that you alert the user to this, possibly with some @echo commands and maybe a pause so they have time to read it. That however goes beyond the scope of this blog.

Here is a link to a much deeper guide about using redirection, with links to many more tutorials about scripting in a shell:
http://windowsitpro.com/article/articleid/20530/shell-scripting-101-lesson-4.html

No comments: