

InterviewSolution
This section includes InterviewSolutions, each offering curated multiple-choice questions to sharpen your knowledge and support exam preparation. Choose a topic below to get started.
1. |
Solve : Making batch files foolproof? |
Answer» Question I want to distribute my batch file. How can I make sure users don't mess up my batch file? Answer It's a fact of life that if it is possible for some knucklehead to mess it up, he/she will. There are three main methods of making sure it doesn't get botched up: 1) Explain how it works before the user uses it, 2) make a help section of the batch, and 3) add protection code to ensure that the user cannot screw up. 1. Create a readme file Include a readme to go with your batch file, explaining the syntax, its uses and limitations. This, however, is the least reliable method, as very few people actually read it, no matter how much you tell them to read it. However, some might, and anyone that reads your readme will benefit (assuming good info is in the readme and that it's easy to understand). 2. Create a help section in your batch file It's as easy as creating a LABEL and liberally using the ECHO command. You could make it so that the user would trigger the help section if they made a syntax error. This section would have ideally the same info as the readme. This is more likely to be seen; however, there will still be a chance of a logic error that will slip through even the best of syntax error catchers. 3. WRITE code to catch errors in the usage of the batch file Though you should include at least #2 (it is also recommended that you include #1, it's not hard), this is the most sure-fire way of making sure the user cannot damage his/her system. However, it is also the most involved of the three procedures, and usually will double or triple the file length. This should not, however, concern you. What should concern you is how to write the code in a way that is effective and serves a good purpose. Let's take a look at an example. A user has an old version of the prompt not equipped with the move.com file that allows you to move files in DOS. This user (Average Joe) has to copy and delete the original. Mr. Joe wants his buddy to write a batch file that allows him to do what newer versions of the prompt can do. Let's say I am that buddy. The easy way out would be to write a batch file with two lines: Code: [Select]copy %1 %2 del %1 But this has its problems as well. What if Joe puts a directory name in, but not the filename! What happens? The file is COPIED to a file with the same name as the directory, and the original is erased! Well, no big deal, right? Just rename it to have a .txt or .jpg or whatever extension, right? However, this is inherently inefficient and causes grief as there is no message saying it was copied incorrectly, and it may take time for Joe to figure out he goofed. The best way to look at writing security for a batch file is to think of all the ways it can go wrong. So, I think about the different ways the copy command can go bad:
And of course:
Easy enough to check with the following: Code: [Select]IF EXIST %1 GOTO DestCheck ECHO The file you wish to copy cannot be found. Make sure that you have ECHO not misspelled your file name and that it does exist. If the source file exists, it will go to a label marked DestCheck (covered next). The two ECHOs are skipped. However, if the file does not exist, the user is informed of this. II. Destination directory does not exist Not at all hard to do. I check the directory by attempting the copy the user wishes to make: Code: [Select]copy %1 %2\%1 IF ERRORLEVEL 0 GOTO DeleteSource ECHO The directory you wish to copy to does not exist. ECHO Please pake sure you have not misspelled the directory name. This code block will attempt to copy the source to the directory, naming the file the same. (Note: This batch file does not support multiple file copies very well and your readme/help section should note this) If the errorlever (amount of errors) is equal to 0 (no errors), then go to the label that erases the source file; otherwise, notify the user there was an error. III. User attempts to copy to a file that already exists This is easy to check, and only slightly more complicated to solve. I find any pre-existing files with the block Code: [Select]IF EXIST %2\%1 GOTO Duplicate and the label "Duplicate" would have the following code: Code: [Select]ECHO The destination file already exists. The file name ECHO will be changed to prevent overwrite. III. User does not specify source/destination I simply check to see if %1 is empty with this: Code: [Select]IF %1=="" GOTO help IF %2="" GOTO help That's it! If %1 is empty, or if %2 is empty, go to the help section. Putting it together Each block does next to nothing by itself. I have to assemble it in a way that makes sense. However, to do this requires me to declare two variables: %1 and %2 need to be given variables so the values can be modified. Code: [Select]@ECHO OFF IF "%1"=="" GOTO help REM - The below I switch makes the string comparison case insensitive IF /I "%1"=="help" GOTO help IF "%2"=="" GOTO help SET source=%1 SET dest=%2 SET error= IF EXIST %source% GOTO DuplicateCheck ECHO The source file does not exist. Please make sure the name is ECHO spelled correctly and the file exists. GOTO End :DuplicateCheck IF NOT EXIST %dest%\%source% GOTO CopyAttempt IF "%error%"=="1" GOTO RenameLayer2 IF "%error%"=="2" GOTO Crash ECHO The destination file already exists. The name of the destination ECHO file will be altered to prevent overwrite. The extension of the ECHO file will be changed; you must re-enter the correct extension yourself. PAUSE SET source=xxyyzzabc.one SET error=1 cls GOTO DuplicateCheck :RenameLayer2 ECHO The name chosen for alteration already exists. ECHO A new name is being chosen. SET source=yxba.two set error=2 GOTO DuplicateCheck :Crash cls ECHO The destination folder has maxed out on the number ECHO of renamed files it may contain. Please rename one ECHO or both of these files with the extension ".one" or ECHO ".two". Xmove will now close. GOTO End :CopyAttempt COPY %1 %dest%\%source% IF ERRORLEVEL 1 GOTO NoDirectory ECHO Copy completed SUCCESSFULLY. Deleting source... GOTO DeleteSource :NoDirectory cls ECHO The directory you chose does not exist. Please ECHO make sure the directory you chose exists and ECHO that you did not misspell the name. GOTO End :DeleteSource DEL %1 cls ECHO The move was completed successfully. GOTO End :help ECHO MOVE.BAT syntax: ECHO MOVE [source] [directory] ECHO. ECHO Note that this file does not support more than one file being copied at a time. ECHO It will work, but the resulting name will be "wrong". Also note that if you try ECHO to move to a file that exists, the batch will attempt to change the name of ECHO the file. It will not allow you to copy to a directory that does not exist. GOTO End :End And I was done, having a perfectly good replacement for move.com. Phew! That's one long code for a simple concept of moving files. However, it makes sure that there is no possible way that the user can cause himself headaches (although renaming the .one and .two files takes a little work). Another important notice As you may know, batch files must be in a folder included in the PATH variable in order to work outside of that folder. A folder that is always in the PATH variable is System32; make sure the user knows about this, EITHER in your readme, in the place where the file is attached/hosted, or in the help section (since it can run in the folder it's in without modifying the PATH variable).This is just one example. The general rule for other batch files is to think of every possible way the user can be a complete bonehead, then take steps to prevent it. This concept applies to all programming, from batch to C++ to FORTRAN and even Assembler. For any out there who use a version of the prompt that doesn't have move.bat, or if you want to use this batch for fun, I have attached the batch file. If you read what I wrote in the help section, there is no need for a readme. This post and attachment has been edited 4 times. Reasons: code error fixed; code error fixed; added cls to code; prevented infinite loop and fixed abnormal screen clearing [old attachment deleted by admin] |
|
2. |
Solve : MS-DOS Tutorial? |
Answer» Deleting entire directory trees The Windows GUI uninstall feature hardly removed anything. Or, you're in the Recovery Console and you're trying to free up space on your hard drvie. Well, this command works perfectly. NOTE: If you are using Windows 2000 or XP, the below command is not for you. Use the RD command with the /S switch. For everything from DOS 5.0 to Windows ME: DELTREE [path] So, if you no longer NEED C:\Program Files\Real and everything in it, do this: DELTREE C:\Program Files\Real WARNING! ALL FILES IN THE SPECIFIED DIRECTORY WILL BE IRRETRIEVABLY ERASED! There is only one switch: /Y. Using this forces the DELTREE to run without prompting for you to give the OK. AUTOEXEC.BAT Some installation instruction requires you to edit the dreaded AUTOEXEC.BAT. Oh no! What are you going to do now? Well, it's really quite simple. AUTOEXEC.BAT contains nothing more than variables with set values. You csn see the list of variables by typing "SET" bar the quotes and pressing [Enter]. It will be a long list. Most of these values should not be modified at all. However, you can add variables without causing harm, and you can also add to the PATH variable without causing any trouble. NOTE TO WINDOWS > 98 USERS: The AUTOEXEC.BAT is no longer a function after Win98. The same function is accomplished in Environment Variables. For all other OS's: Modifying AUTOEXEC.BAT Let's say you want to keep batch files in a directory, and have them work no matter where in your computer you are. Simple, right? Of course it is. Let's say you have your batch files in the same place I do - C:\Batch. To "install" this directory, go into AUTOEXEC.BAT, find the path variable, and go to the last directory. If there is not a semicolon (;) at the end, put one there. Then type the full path of the directory (no spaces in the whole variable). Save and exit. You should be able to use your batch files anywhere you choose. If not, type AUTOEXEC and press enter; you may need to have the PC cycle through the PATH variable again. To add a variable of your own, simply go to the end of AUTOEXEC.BAT, add a new line, and use this syntax: [variable]=[value] Example: color=blue You can also set variables with the prompt, but they only exist for that particular session. If you reboot (or exit, if you're using the Prompt) the variable will be gone. To so this, use the SET command: SET color=red You can set the same variable an infinite number of times, limited only by your boredom with endlessly setting a variable; however, there may be a LIMIT to the number of variables you can set. If you run into this, consider reusing a variable or exiting the session/rebooting (for true MS-DOS). As you will learn in the next lesson, variables are a great asset to the MS-DOS experience. Complex Batch Files (Otherwise known as making the simplest of tasks as confusing as possible) You should know the basics of how to write batch files. As your knowledge of DOS commands grows, so too does the available commands you can use in your batch files. However, there are some commands that can only be used in batch files, or at least only effectively in a batch file. They are some of the most powerful tools available in batch. They are: IF - Executes code only if a certain condition is true. SET - Assigns a variable; in a batch file, can also trigger a special prompt. LABEL - A code block given a special name for reference purposes. GOTO - Code which allows you to go to a specific label. FOR - Code which is executed a certain number of times based on certain conditions. IF IF executes a code block only if a certain condition is true. Typically used with the GOTO command, it makes an excellent way of directing the "traffic" or your code. Example: Let's say you want to do a DIR only if there are files in the directory. This line of code would work: Code: [Select]IF EXIST *.* DIR The IF EXIST function checks to see if the specified files exist. It also can be used to check to see if they don't exist - IF NOT EXIST. IF can also be used to see if an operation worked/can be done. If you want to copy a file but you want to make sure the destination directory exists, use ERRORLEVEL. ERRORLEVEL is normally 0, but will become 1 if ever something goes wrong. So: Code: [Select]COPY blah.txt yada\yada.txt IF NOT ERRORLEVEL 0 ECHO Error: Could not find destination More info on IF covered later. SET - Just like in the prompt, set makes a variable that remains until the end of the DOS session (meaning typing the SET command after the batch is executed will show this new variable). Example use: What if you wanted to change directory to the A: drive, and back? Well, how would you know where "back" is, if you have 100+ directories on your PC? And what about other PC's? You can't just guess at it. You can do this: Code: [Select]SET CurrDIR=%cd% A: [do stuff] cd %CurrDIR% The %cd% variable is the current directory. But when you change directories, %cd% changes. However, saving the %cd% in another variable that does not change allows you to go back to where the user was before. SET can also be used to make custom prompts, allowing the user to make choices. An example: User can choose between opening AUTOEXEC.BAT, going to A:, or going to C:. Choices can be displayed with the ECHO command, and SET is used to create a custom prompt: Code: [Select]ECHO What would you like to do? ECHO. ECHO 1. Open AUTOEXEC.BAT ECHO 2. Go to A: ECHO 3. Go to C: SET /P CHOICE="Enter 1/2/3>" The /P switch creates a prompt, and CHOICE is a variable. The value in quotation marks is what is displayed at the prompt. When the user types something and presses ENTER, the variable is changed to whatever they entered. Because of this, you can use the IF command to check if the number that was entered is valid. It also allows you to GOTO a certain label based on what was chosen. For this example, string comparison will be used. String comparison is simply comparing two variables or two strings or one variable and one string to see if they are equal. Code: [Select]IF "%CHOICE%"=="1" AUTOEXEC IF "%CHOICE%"=="2" A: IF "%CHOICE%"=="3" CD C:\ LABEL - The best (and only) way to effectively manage what code gets executed, and when. Labels are made by putting text on a line of its own and preceding it with a semicolon (:). It should be one word only. Examples are: :Begin :ExecuteCopy :Error :1 :Orange :Zebra They can really be anything. They are used with GOTO. GOTO - Used to "go to" the specified label. So, if your code read like this: Code: [Select]GOTO End ECHO Hi! :End You would never see the word "H1!" as it is skipped. This can be used to create sections of code that handle errors, other sections to check for errors, etc.. It's a good IDEA to put the label "End" at the end of all your batchfiles, so whenever you need to terminate the batch file, you can just GOTO End, and you will effectively end the batch file. Continued on next post...FOR - The FOR loop has a wide range of uses. It's main purpose is to execute a command for all files/directories that meet a certain standard. The syntax: FOR {switch} %%variable in (set) do [command] Switches available: /D - Directories only; only directories are valid answers /R - Executes command in all subdirectories. Syntax is a LITTLE different: Code: [Select]FOR /R [drive :][path] ...The ... is the normal syntax for FOR. /F - used to parse a file. The syntax for it is: Code: [Select]FOR /F "keywords" %%variable(s) in (filename) do [command] Replace "keywords" with as many of these as you need: eol=c - End Of Line character (one character). Lines with this at the beginning are a comment and not parsed. Replace "c" with desired character. skip=n - Replace "n" with a number. n number of lines are skipped at the beginning of the file. tokens=1,2,3-7 - Specifies which lines are parsed. At least two must be there. 1,2 would do first and second lines, 1,3 would leave out every second line, etc.. The "3-7" in the example would parse every fourth through seventh line. Place a * at the end if results are not what you expect; that may fix it. %%variable is the first variable to be used. The number of tokens you use is how many variables are added by the FOR command. So, if you started with %%a and used tokens 1 and 2, you would have %%a, %%b and %%c. (set) is whatever you want. It can be a text file (for use with /F), it can be a directory, or even a text string. It's up to you. How /F works with tokens In our example, we have the following: Code: [Select]FOR /F "tokens=1,2*" %%i in (file.txt) %%i is set to the first line of file.txt, %%j is assigned to the next line, etc.. This is repeated until the file is parsed. So, the correct code would be: Code: [Select]for /F "tokens=1,2*" %%i in (file.txt) do echo %%i %%j %%k Assuming @ECHO OFF is at the top of the batch, the output would be to echo the entirety of the file. Another example: Let's say you wanted to save all the file names in a directory into a text file, but don't want the clutter of a DIR. You could do this: Code: [Select]FOR %%A in (*.*) do ECHO %%A >> for.txtGRAPHICAL interfaces for batch files So, you wanna make a cool looking box to put your batch file in? You want it to look something like this?: Well, you need to use some extended characters in the ASCII Dos-Extended Character Set. No matter how much you hate the EDIT window, you must use it to make a graphical interface. No exceptions. It is advised that you hit the [Insert] key during graphical design so you don't end up with a vertical line moved a long way away from the table you are making. Also, there are many more extended characters that only work in EDIT. See the full list here. IV. Reference All posts below this one are additional topics for reference on various "fads" commonly being asked about in the DOS/Programming forums at the time of writing. Because of the changing fads, all users will be welcome to add references to this thread, and I will add hyperlinks and adjust formatting as necessary (please respect the bold header for each post and underlined sub-topics, it makes it easier for me). The DATE variable If you need the date for anything at all, use the variable %DATE%. To find the date's format, type at any prompt: ECHO %DATE% As of this writing, the echo'd text is: Sun 05/14/2006 But what if you only want part of this? You can use the ~ modifier to change what you get. The syntax is: %[variable]:~[starting character],[number of characters] For example, to just get the date without the day, you would use ECHO %DATE:~4% The characters start at 0, like this: Wed 02/14/2007 0123456789 <--etc... The code parses the DATE variable, starting with character 4 (the first character is zero). Since there is no comma and nothing after that, it simply finishes displaying the variable from that point. What if you wanted to ECHO just the numbers, or use that as a file (05142006)? Well, try this: ECHO %DATE:~4,2%%DATE:~7,2%%DATE:~10% Doing this will echo just the date without any spacing at all. |
|
3. |
Solve : Date manipulation? |
Answer» Manipulating dates in the WINDOWS XP Command window. The ability to manipulate dates in BATCH scripting is very limited. Day, Month and Year can be extracted from either the 'date /t' command or the %date% environment variable only if the date format is known. Returning dates in advance of, or prior to, today's date requires many LINES of coding to check for such things as a new month, new year, leap year etc. The following two codings will extract day date month and year from the date format day mm/dd/yyyy. Code: [Select]@echo off cls FOR /f "tokens=1-4 delims=/ " %%a in ('date /t') do ( set day=%%a set mm=%%b set dd=%%c set yy=%%d ) echo %day% %dd% %mm% %yy% Code: [Select]@echo off cls set day=%date:~0,3% set mm=%date:~4,2% set dd=%date:~7,2% set yy=%date:~-4% echo %day% %dd% %mm% %yy% Returning dates in advance of, or prior to, today's date. If one wanted to use a date which was 3, 30 or even 300 days ago or hence it is BEST achieved using a scripting language other than batch script. Visual Basic Scripting language (VBS) is a built-in feature of Windows XP so for those who do not like to install programs/routines on their pc the following code gives the opportunity to manipulate dates to suit individual requirements. (Only one small temporary file is created in the %Temp% folder and is deleted when no longer required). VBS is used in conjunction with batch scripting to extract/display the various components of the date. The code will be successful with any date format. Code: [Select]:: ACKNOWLEDGEMENT. Dias de verano for his input to set up the .vbs file. :: Syntax: filename only - set/display today's date. :: filename -n - set/display today's date minus n days. :: filename +n - set/display today's date plus n days. @echo off cls :: Check for incorrect commandline entry.. set a=%1 if "%a%"=="" goto start if "%a:~0,1%"=="+" goto start if "%a:~0,1%"=="-" goto start echo.&echo. echo Incorrect entry - run aborted echo. echo Press any key to continue.... pause > nul cls & exit/b :: Create/run temporary .vbs file (extracts date components). :start set vb=%temp%\newdate.vbs ( echo Newdate = (Date(^)%1^) echo Yyyy = DatePart("YYYY", Newdate^) echo Mm = DatePart("M" , Newdate^) echo Dd = DatePart("D" , Newdate^) echo Wd = DatePart("WW" , Newdate^) echo Wn = DatePart("Y" , Newdate^) echo Ww = datepart("W" , Newdate^) echo Wscript.Echo Yyyy^&" "^&Mm^&" "^&Dd^&" "^&Wd^&" "^&Ww^&" "^&Wn )>>%vb% FOR /F "tokens=1-6 delims= " %%A in ('cscript //nologo %vb%') do ( set Yyyy=%%A set Mm=%%B set Dd=%%C set Week#=%%D set Weekday#=%%E set Day#=%%F ) del %vb% :: [Environment Variables are: :: %Yyyy% Year in the format yyyy :: %Mm% Month in the format m or mm :: %Dd% Number of the day in month in the format d or dd (range 1 thru'31) :: %Week#% Week number in year in the format w or ww (range 1 thru' 52) :: %Weekday#% Day number in week in the format w :: (range 1 thru' 7, day#1 is Sunday) :: %Day#% day number in the year in the format d thru ddd :: (range 1 thru' 366)] set days= if not "%1"=="" set days=days if %Mm% lss 10 set Mm=0%Mm% if %Dd% lss 10 set Dd=0%Dd% :: The following code serves to demonstrate just two of the formats which can be displayed. echo.&echo.&echo.&echo.&echo.&echo. echo Date to be displayed is today %1 %days% echo. echo Example of date in yyyy/mm/dd format: %Yyyy%/%Mm%/%Dd% echo " " " " mmddyyyy " : %Mm%%Dd%%Yyyy% echo.&echo.&echo. echo Press any key to continue... pause > nul cls & exit /b For those who have no objection to installing a small utility in order to manipulate dates please download DOFF.ZIP from http://www.jfitz.com/dos/index.html and unzip it into your Path - the code below will be successful with any date format. Code: [Select]@echo off cls :: Syntax: filename only - set/display today's date. :: filename -n - set/display today's date minus n days. :: filename +n - set/display today's date plus n days. for /f "tokens=1-3 delims=/ " %%a in ('doff mm/dd/yyyy %1') do ( set mm=%%a set dd=%%b set yyyy=%%c ) :: The following code serves to demonstrate just two of the formats which can be displayed. set days= if not "%1"=="" set days=days echo.&echo.&echo.&echo.&echo.&echo. echo Date to be displayed is today %1 %days% echo. echo Date in the format dd mm yyyy %dd% %mm% %yyyy% echo.&echo. echo Date in the format yyyy/mm/dd %yyyy%/%mm%/%dd% To view some of the capabilities of Doff.exe after unzipping it into your Path, at the Command Prompt enter: Doff dd returns the day only Doff mm returns the month only Doff yy returns the year only e.g. 08 Doff yyyy returns the year only e.g. 2008 Doff ddmmyy returns the day month and year e.g. 231008 Doff mmddyyyy returns the month day and year e.g. 10312008 Doff ddmmyyyy -30 returns today's date minus 30 days Doff mmddyyyy +300 returns today's date plus 300 days for /f %%I in ('doff yyyymmdd +10') do echo %%I will return todays date +10 days in the format yyyymmdd Note that throughout the above codings syntax checking is minimal or non-existent. If the syntax of any command-line entry is incorrect the results are unpredictable. Good luck. |
|
4. |
Solve : Common CMD Commands? |
Answer» Here is a list of commands that you can run off from the Run Command prompt in XP: |
|
5. |
Solve : Fn keys in CMD.EXE? |
Answer» Windows XP. |
|