Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / batch

Batch file caveat when running as administrator

4.00/5 (1 vote)
1 Mar 2011CPOL2 min read 21.6K  
Are you sure your batch file will actually do what you intended?

Introduction

This tip explains a certain danger in running batch files or command scripts as administrator. It is applicable to systems running Windows Vista or higher, with user account control enabled.

Background

I frequently use batch files to clean up unnecessary files (build targets, settings, etc.), and running it as administrator very nearly wiped out my OS. I'm publishing this to warn others who may commit the same mistake.

Details

What danger?

To put it simply, when you run a batch file as administrator, the working folder changes to %SystemRoot%\system32 (which is usually C:\Windows\system32) [1].

Demo

To check it out for yourself, create a simple batch file with the following content, and name it anything you like, say test.bat.


@cd
@pause

Now run the file by double-clicking it. Note the path displayed, it should be the folder where the file is saved. Now run it again as administrator - right click the file and select run as administrator (or whatever it is in your local language). The path shown will be different.

C:\Windows\system32
Press any key to continue...
Figure: Sample output when run as administrator

Explanation

This is really beyond the scope of the tip, but in case you want to know:

  • cd without parameters prints the current directory (the working directory of the file in this case)
  • pause keeps the console window from closing, so that you can see the above output
  • @ at the beginning of each command prevents the command itself from being echoed (try it without the @ to see what I mean).

Note: The command echo off in the example below does the same thing, it prevents echoing of all commands after it. The @ there prevents that command itself from being echoed.

Fix

Not a fix really, just a sanity check you may consider using. If the file is named as above, at you could do the following:


@echo off
if not exist test.bat goto _ERRROR

 rem The actual work of the file is done here

goto _END

:_ERROR
echo Invalid directory!

:_END

Explanation

The if statement at the top checks whether the batch file itself exists in the current folder. If you are running as administrator, the working folder will be something else, so the condition will be true, and control will be passed to the _ERROR label, skipping everything.

This is just one example off the top of my head, you may use any variation you like.

That's it, and run safely!

--
Update

See the alternate below by Reto70 for a better method than my error checking.

--
[1] Checked on several systems. 64 bit OS may differ, not checked.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)