Thursday 2 May 2013

Windows Commandline & Batch file tricks Part 1

Here are some little useful Windows command line tricks that could be used in batch files. 


This example will loop only a set number of times, Also useful for counting the number of times a loop has run.

@echo off

 set counter=1

:loop
 echo looped %counter% times
 echo do something
 if %counter% == 10 goto end 

 set /a counter=%counter% +1
goto loop

:end 
 echo Loop ran %counter% times



Filename friendly date, Sometimes you want to use the current date to generate a filename so can't use %date% as you normally get something like "Thu 16/05/2013". An easy way to reformat it to YYYYMMDD is as below.   


@echo off
 set today=%date:~10,4%%date:~7,2%%date:~4,2%
 echo %today%

 echo and a sample file
 echo %date% %time% >>%today%.log




Detect if Windows 32/64 bit. Some times you need to know if the script is running on a 32 bit or 64 bit version of Windows from the commandline. This allows the scripts to do different things depending upon the version of Windows.(Like use the "C:\Program Files (x86)\"path instead of "C:\Program Files\") 


@echo off
if defined ProgramFiles(x86) (
 echo Is 64 bit version of windows
) else (
 echo Is 32 bit version of windows
)