Announcement

Collapse
No announcement yet.

my first batch file critique

Collapse
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • my first batch file critique

    OK, I've done some reading on the "Windows command line" and had a need come up at work where I could actually apply what I've read.

    Basically I need to copy a bunch of files from various places on the network to the local computer and then on Fridays also run a backup job.

    System is XP Pro.
    I copied choice.exe from one of the servers to the %windir%\system32 folder so I could use the choice command.

    This is the first script I've actually written. I usually just searched the net and found something that did the job but I really didn't understand the commands that made it work.

    Here's the code.
    Code:
    @echo off
    
    rem checks for marker file
    if EXIST %systemdrive%\nickBackupScriptMarker.txt (goto START) else echo . > %systemdrive%\nickBackupScriptMarker.txt & goto START
    
    :START
    REM Set variables for backup set name, filename, and day
    set backName=NT Backup Created %DATE%
    for /f "tokens=1-4 delims=/ " %%a in ("%date%") do (set fileDate=%%a_%%b-%%c-%%d & set day=%%a)
    
    rem checks if copy over alread ran if on Friday
    for /f "tokens=1,2" %%a in (%systemdrive%\temp\nickBackupScriptMarker.txt) do (if "%%a %%b"=="%date%" (goto CHOICE1) else goto COPY)
    
    
    :COPY
    
    REM ********************************************************
    REM      the live script contains about 10 xcopy commands
    REM      here that copy various files to single a directory
    REM ********************************************************
    
    
    rem on Friday, writes the date to the marker file
    if "%day%"=="Fri" (echo %date% > %systemdrive%\nickBackupScriptMarker.txt & goto CHOICE2) else goto EXIT
    
    
    
    :CHOICE1
    echo You have already copied over today.
    echo Would you like run a backup instead?
    echo.
    echo 1. To run the backup  ...press 1
    echo 2. To copy over again ...press 2
    echo 3. To cancel          ...press 3
    choice /c 123
    if "%errorlevel%"=="1" (goto BACKUP) else (if "%errorlevel%"=="2" (goto COPY) else goto EXIT)
    
    :CHOICE2
    choice /c yn /m "Do you want to backup to the Zip drive now?" 
    if "%errorlevel%"=="1" (goto BACKUP) else goto EXIT
    
    :BACKUP
    echo Make sure a Zip disk is in the drive and then
    pause
    format e: /q /y
    C:\Windows\system32\NTBACKUP.EXE backup "@C:\weekly.bks" /n "%backName%" /d "%backName%" /v:no /r:no /rs:no /hc:off /m normal /j "Nick's Backup Job" /l:s /f "E:\%fileDate%.bkf"
    
    
    :EXIT
    I've tested it and everything works but if anyone has any pointers or comments it would be much appreciated.
    Regards,
    Jeremy

    Network Consultant/Engineer
    Baltimore - Washington area and beyond
    www.gma-cpa.com

  • #2
    Re: my first batch file critique

    Great batch Jeremy
    thank you for sharing

    Good example of how to use and refresh a "marker file" from a batch for checking whether to run a certain command or not.

    nice how you use chained commands command1 & command2, and use parentheses (... ...) to form groups of command sets.
    Using "choice.exe" from Windows server is a good idea since choice.exe is not available in Windows XP and Windows 2000. By using Choice.exe you have nicer menu's options, and it looks a little bit nicer than to use Set.exe /P (see example).

    I think there is one typo in your batch though, in line 12, "temp\" shouldn't be in that path!

    For readers who want to run this batch on a Windows XP in an other language there is a change that they have to adjust the two lines:
    In line 9: delims=/ (character that separate the month/day/year or day-month-year)
    In line 24: =="Fri" (must be translated)

    For readers who want to use the default Windows XP way to create a menu (instead of copying choice.exe);
    Here is an example;
    Code:
    @ECHO OFF
    REM example of "User Input in Batch Files"
    CLS
    
    :LOOP0
    ECHO A. Menu item A
    ECHO B. Menu item B
    ECHO C. Menu item C
    ECHO Q. Quit
    :: SET /P prompts for input and sets the variable
    :: to whatever the user types
    SET Choice=
    SET /P Choice=Type the letter and press Enter: 
    :: The syntax in the next line extracts the substring
    :: starting at 0 (the beginning) and 1 character long
    IF NOT '%Choice%'=='' SET Choice=%Choice:~0,1%
    ECHO.
    :: /I makes the IF comparison case-insensitive
    IF /I '%Choice%'=='A' GOTO ItemA0
    IF /I '%Choice%'=='B' GOTO ItemB0
    IF /I '%Choice%'=='C' GOTO ItemC0
    IF /I '%Choice%'=='Q' GOTO End
    ECHO "%Choice%" is not valid. Please try again.
    ECHO.
    GOTO Loop0
    
    :ItemA0
    :LoopA0
    ECHO.
    ECHO commands for Item A0
    SET Choice=
    SET /P Choice=Are you sure (Y/N)?: 
    IF /I '%Choice%'=='Y' GoTo ItemA0y
    IF /I '%Choice%'=='N' GoTo Again Else GoTo LoopA0
    :ItemA0y
    ECHO commands will be here for Item A0=yes.  (...done)
    GOTO Again
    
    :ItemB0
    ECHO commands will be here for Item B0.  (...done)
    GOTO Again
    
    :ItemC0
    ECHO commands will be here for Item C0.  (...done)
    GOTO Again
    
    :Again
    echo. 
    echo "Return to main menu"   (press any key to continue...)
    PAUSE >Nul
    
    CLS
    GOTO Loop0
    :End
    SET Choice=
    cls
    
    exit

    \Rem

    This posting is provided "AS IS" with no warranties, and confers no rights.

    __________________

    ** Remember to give credit where credit's due **
    and leave Reputation Points for meaningful posts

    Comment


    • #3
      Re: my first batch file critique

      Thanks Rems.
      Originally posted by Rems View Post
      I think there is one typo in your batch though, in line 12, "temp\" shouldn't be in that path!
      Yes, you're absolutely right. I must have pasted from an older version prior to correcting that.

      Thanks for the example! It didn't even occur to me to use the SET command like that. And I didn't even know about expansion. So much to learn.

      I noticed that you cleared your variable at the end of the batch and used the exit command. Is that the proper way to do things? Won't it exit automatically and clear the variables automatically?
      Regards,
      Jeremy

      Network Consultant/Engineer
      Baltimore - Washington area and beyond
      www.gma-cpa.com

      Comment


      • #4
        Re: my first batch file critique

        Originally posted by JeremyW View Post
        I noticed that you cleared your variable at the end of the batch and used the exit command. Is that the proper way to do things? Won't it exit automatically and clear the variables automatically?
        In your batch it is not nesserary to clear the temporary environments. Environments will be available to only that batch file execution and will be automaticly cleared when the batch itself is finished.
        I cleared %Choice% in my example because this batch-example was limited only to show how to use User input, if it was a real batch there could be more code after that part. Then if %Choice% is used later on in that batch again is a good practise to reset the previous choice. An other reason to clear environment variables or re-using the same name again during batch file execution is because environment space is limited.

        There are several ways to end batch file execution, like reaching the end of the batch file, starting execution of another batch file, or using the EXIT or GOTO:EOF commands. It is just a habit of me to use Exit in unfinished batches or if applications were executed from the batch, there is no actual need for using Exit here. I use Exit simply because a simular code (wscript.quit) it very common in vbscripts.


        Related Commands:
        - Manipulate environment variables: www.robvanderwoude.com/batchcommands.html#SET
        - Run a command in a separate process: www.robvanderwoude.com/batchcommands.html#START

        \Rem
        Last edited by Rems; 11th April 2007, 00:02.

        This posting is provided "AS IS" with no warranties, and confers no rights.

        __________________

        ** Remember to give credit where credit's due **
        and leave Reputation Points for meaningful posts

        Comment


        • #5
          Re: my first batch file critique

          Thanks Rems. That's great info for a beginner like me.
          Regards,
          Jeremy

          Network Consultant/Engineer
          Baltimore - Washington area and beyond
          www.gma-cpa.com

          Comment


          • #6
            Re: my first batch file critique

            Hi, Jeremy.
            I'd like to slide a bit (if it's OK with you) to the philosophical side here, with two questions:
            1) Is there a reason for using batch files? They have some disadvantages compared to other forms of scripts:
            - I know that from all the scripting methods, they are the slowest to be executed. Probably because they load the command shell;
            - they use command-line commands, that are poor in options and possibilities;
            2) What extension are you using for the file you wrote? Is it .CMD or .BAT? There are some differences between them, that can influence more the performance of the file:
            - .CMD calls the CMD.exe, the newer 32-bit command shell. .BAT calls the Command.COM, the 16-bit version. Although this is controversial, some are certain about it, some consider it an "urban myth". Never checked it, so cannot tell you for certain.
            - if the command shell extensions are enabled, some commands used with CMD.exe set the errorlevel to 0 if the command succeeded, while the same in Command.Com don't. Such commands are SET and ATTRIB.

            I also found this site, looks promising: http://commandwindows.com/batch.htm
            Last edited by sorinso; 11th April 2007, 07:55. Reason: some editing needed...

            Sorin Solomon


            In order to succeed, your desire for success should be greater than your fear of failure.
            -

            Comment


            • #7
              Re: my first batch file critique

              Originally posted by sorinso View Post
              Hi, Jeremy.
              I'd like to slide a bit (if it's OK with you) to the philosophical side here, with two questions:
              By all means. That's why I started this thread.

              1) Is there a reason for using batch files? They have some disadvantages compared to other forms of scripts:
              - I know that from all the scripting methods, they are the slowest to be executed. Probably because they load the command shell;
              - they use command-line commands, that are poor in options and possibilities;
              The reason for using a batch file is twofold a) I didn't know any better b) batch is what I've been reading up on.

              2) What extension are you using for the file you wrote? Is it .CMD or .BAT? There are some differences between them, that can influence more the performance of the file:
              - .CMD calls the CMD.exe, the newer 32-bit command shell. .BAT calls the Command.COM, the 16-bit version. Although this is controversial, some are certain about it, some consider it an "urban myth". Never checked it, so cannot tell you for certain.
              - if the command shell extensions are enabled, some commands used with CMD.exe set the errorlevel to 0 if the command succeeded, while the same in Command.Com don't. Such commands are SET and ATTRIB.

              I also found this site, looks promising: http://commandwindows.com/batch.htm
              I'm using .bat as the extension. I'll have to research that.

              Many thanks for the feedback.

              BTW - in my reading I did learn that cmd.exe is 32-bit and command.exe is 16-bit.

              EDIT - Sorin, in my research I've found that .bat and .cmd are the same thing save the actual file extension. They both use cmd.exe and Windows views them as the same thing according to the registry.
              Last edited by JeremyW; 11th April 2007, 16:30.
              Regards,
              Jeremy

              Network Consultant/Engineer
              Baltimore - Washington area and beyond
              www.gma-cpa.com

              Comment


              • #8
                Re: my first batch file critique

                Originally posted by Sorin
                - .CMD calls the CMD.exe, the newer 32-bit command shell. .BAT calls the Command.COM, the 16-bit version. Although this is controversial, some are certain about it, some consider it an "urban myth". Never checked it, so cannot tell you for certain.
                There is a confusion
                In fact if the Windows version supports cmdfiles then it will always use the 32 bit "command shell" (cmd.exe) by default, even if you gave a .bat extension to the file.
                The older 16 bit command processor command.com ("MS-DOS command prompt") is supplied only to provide backward compatibility for 16 bit DOS applications. Windows executes this shell within a virtual DOS machine (VDM).
                Only the nonNT_versions of Windows use command.com to run batchfiles, and these versions do not support the .cmd file extension.

                Newer versions of Windows support new or newer versions, of batchcommands and utilities, now to ensure that a batch file will not run on a Windows 95/98 machine you should use the extension .CMD rather than .BAT.
                When the script must run (and can run) on both NT- and nonNT_versions of windows then you, of course, must always use the BAT extension for a batch file. :-p

                And when a script -that is written to run on both windows types- containes a line(s) where it opens a new or a nested command shell from within the script, then you must use %comspec% /c OR %comspec% /k to run the command. That is what you see mostly used in vbscript when running a shell command. The value of %comspec% is automatically the right command shell executable (cmd.exe or command.com) for the current Windows version.

                By my knowledge
                A batfile will not sets a %errorlevel% for commands like PATH, APPEND, PROMPT, SET and ASSOC, it only sets ERRORLEVEL on errors.
                But a cmdfile can sets these ERRORLEVELs. You can disable it for cmdfiles too by disabling "Command Extensions" functionality for CMD.exe. This is controlled by setting a value in the registry: HKCU\Software\Microsoft\Command Processor\EnableExtensions. Alternatively under Win XP you can run CMD /e:on or CMD /e:off .
                But of course it is possible that this difference between cmd- and bat-files is also part of the same evolution confusion, never tested it.

                more
                - Frequently Asked Questions Regarding The Windows 2000 Command Processor
                - The Windows NT Command Shell
                - Command shell overview



                -> Scripting Languages:
                Both batch- and vbscripts are interpreted and need a host to execute, meaning they both are not compiled to run more efficient.
                The choice of using batch or VB is more often a personal choice than the question which of the two is faster for a particular job. If there is a job to be done, one person can see possibilities in a batch solution the other finds it in a visualbasic way, depending on your personal skills.
                Sometimes a batch file can do the same only with one single command line where vbscripts needs at least 4 lines of code.
                Or you can choose for a batch because for how it runs, how you can use menus and labels and finding the language more intuitive because of the commands and utilities.

                Vbscript is a high-end ActiveX based scripting language. There for is has more power and flexability to create 'small computer programs'.


                \Rem

                This posting is provided "AS IS" with no warranties, and confers no rights.

                __________________

                ** Remember to give credit where credit's due **
                and leave Reputation Points for meaningful posts

                Comment


                • #9
                  Re: my first batch file critique

                  Ah yes, there is a difference between .bat and .cmd and what you say, Rems, is right.

                  Save this as as .bat and .cmd then run them and see what the output is.
                  Code:
                  @echo off&setlocal ENABLEEXTENSIONS
                  call :func&&echo/I'm a cmd||echo/I'm a bat
                  goto :EOF
                  
                  :func
                  md;2>nul
                  set var=1
                  Check out this thread for a good discussion on it. http://www.pcreview.co.uk/forums/thread-1466057-1.php
                  Regards,
                  Jeremy

                  Network Consultant/Engineer
                  Baltimore - Washington area and beyond
                  www.gma-cpa.com

                  Comment


                  • #10
                    Re: my first batch file critique

                    Originally posted by JeremyW View Post
                    Check out this thread for a good discussion on it. http://www.pcreview.co.uk/forums/thread-1466057-1.php

                    I remembered right, then, about the 32-bit and 16-bit dispute... I read that thread some months ago, when the issue was raised on one of the posts in this forum. Somehow, I didn't manage to see it this time...
                    I did a test for the CMD vs BAT running shell: using ProcessExplorer, I ran the same batch once with BAT extension and once with CMD. In both cases, the cmd.exe was involved. Thus, this really IS a myth. (Man, why didn't I check this before?)
                    Regarding not knowing something else, I can suggest you check Microsoft's Webcasts Archive: http://www.microsoft.com/technet/scr...s/archive.mspx . You have there webcasts from Scripting Week 2 years ago. I downloaded all the stuff from the first two weeks and watch them offline, and it is a good starting point. As you probably saw from my thread in this forum, I myself am making the first steps in scripting. And the webcasts are a very good start.
                    And there is, of course the sticky thread with the useful resources: http://forums.petri.com/showthread.php?t=300.

                    Sorin Solomon


                    In order to succeed, your desire for success should be greater than your fear of failure.
                    -

                    Comment


                    • #11
                      Re: my first batch file critique

                      Difference between .cmd and .bat myth busted!




                      Originally posted by Sorin
                      I can suggest you check Microsoft's Webcasts Archive: http://www.microsoft.com/technet/scr...s/archive.mspx . You have there webcasts from Scripting Week 2 years ago. I downloaded all the stuff from the first two weeks and watch them offline, and it is a good starting point.
                      Yes, I like the MS webcasts, although never watch them to the end. You have to bring some pizza and cola along with it.

                      From the scripting_week casts I downloaded some time ago:
                      • Trading Scripts (Level 200)
                      • Look, Mom, I’m a Scripting Guy! (Level 200)
                      I found them very learnfull

                      Good tip Sorin!
                      can you add that link also to the webcasts to the sticky thread?

                      \Rem
                      Last edited by Rems; 12th April 2007, 18:11.

                      This posting is provided "AS IS" with no warranties, and confers no rights.

                      __________________

                      ** Remember to give credit where credit's due **
                      and leave Reputation Points for meaningful posts

                      Comment


                      • #12
                        Re: my first batch file critique

                        : Great show, MythBusters!

                        bring some pizza and cola along with it
                        That's exactly the reason I downloaded them, to watch them offline. This way, I watch whenever I have few spare minutes. It took me few days to finish the first one
                        can you add that link also to the webcasts to the sticky thread?
                        You asked so nicely, how could I refuse? Done!!

                        Sorin Solomon


                        In order to succeed, your desire for success should be greater than your fear of failure.
                        -

                        Comment

                        Working...
                        X