Sunday, 11 August 2013

Batch File Creation - Basics

       To create a batch file, open a notepad and save the file with an extension of  ".bat". Type the cmd in run and enter , execute the batch file by drag and drop the .bat file into the command prompt and pass the parameters.

Let we start with some basics .

     keyword REM indicates that this line is a comment by using this we can specify the comment for what usage the code is written.
                      REM test 

keyword @echo off indicates that this will stop the several lines of repetitive output from showing
                      @echo off

keyword %1, %2 indicates there are two input parameters for the batch file
                      START %1



Example 1
  Launch a website in default browser

  REM Launch a Website in default browser by getting the input from user
    @ECHO OFF
    START %1
    @ECHO OFF

  Type following line in command prompt, Now you can see the website is launched in default browser.
         C:\test.bat www.dotnetvisio.blogspot.com



Example 2
  Launch a website in specified browser

  REM Launch a Website in specified browser by getting the input from user
    @ECHO OFF
    START /D "C:\PROGRAM FILES (X86)\INTERNET EXPLORER" IEXPLORE.EXE %1
    @ECHO OFF

  Type following line in command prompt,now you can see the website is launched in specified browser.
         C:\test.bat www.dotnetvisio.blogspot.com 



Example 3
  Copy a File from a path to desktop

  REM Copy a file from specified path to desktop
    @ECHO OFF
    COPY %1 %USERPROFILE%\DESKTOP
    @ECHO OFF

  Type following line in command prompt,to copy a specified to desktop
         C:\test.bat "c:\c#.pdf"



Example 4
  Iterate to the parent directory and moved to the adjacent directory and change the parent directory.

:: Changes from the current directory to an adjacent directory or to the parent directory
@ECHO OFF
ECHO Batch started

IF "%1" == "1" GOTO Parent-1
IF "%1" == "2" GOTO Parent-2
IF "%1" == "3" GOTO Parent-3

:Parent-1
CD ..\%2
GOTO END

:Parent-2
CD ..\..\%2
GOTO END

:parent-3
CD ..\..\..\%2
GOTO END

:END
      CD %dir%

Input :
                                                                                                                           
         C:\Users\s\Desktop\test.bat 1 documents                                                          


output:

  Batch Started                                                                                                            
      C:\Users\s\Documents