Batch files are well known for managing and configuring client computers. Most of the system administrators are creating batch files on a regular basis for completing tasks for which they otherwise be doing them manually and therefore taking up a lot of time.
Recently I was requested to check if all the client computers were running a program on startup.
Querying the register
Windows puts the startup entries in the register. In this case the entry should be in
To get the entries in this register key we can do a register query:
reg query HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run\
Which will show:
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run start REG_SZ \server\scripts\start.bat drives REG_SZ \server\scripts\drives.bat
You can also use this command to check if a specific value exists:
reg query HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run\ /v drives
When the value or keys exists, the entry is showed. If the value or keys doesn’t exists, the system will throw an alert at you:
ERROR: The system was unable to find the specified registry key or value.
Creating the batch file
We know how to query the register, now we need to create the batch file which handles the check.
- Create a new batch file or edit an existing one. In this case we edit start.bat to check if drives.bat is also executed at startup
- Add the following code and suppress the output:
reg query HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run\ /v drives >null 2>&1
>null 2>&1 takes care of suppressing the output.
- Now we need to do something with the result of the check. If the key or value is found the
%ERRORLEVEL%variable will have 0 as value, which means there is no error found, which in this case means the key or value exists. If the key or value isn’t found, the
%ERRORLEVEL%variable will have 1 as value.
With a simple
IFstatement we can check the result of the register query:
if %ERRORLEVEL% == 0 goto end if %ERRORLEVEL% == 1 goto installdrives
- At last we need to add the
installdrivesaction and the
:installdrives reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" /v drives /t reg_sz /d "\server\scripts\drives.bat" goto end :end @exit
That’s it, when the computer runs the batch file, it checks for the register key and if it doesn’t exists it adds it!
Administrator permissions are required for adding keys to the register!
When everything is put together you should have the following code:
@echo off reg query HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run\ /v drives >nul 2>&1 if %ERRORLEVEL% == 0 goto end if %ERRORLEVEL% == 1 goto installdrives :installdrives reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" /v drives /t reg_sz /d "\server\scripts\drives.bat" goto end :end @exit