Results 1 to 2 of 2
  1. #1
    Join Date
    Oct 2005

    Unanswered: DOS Command/Batch File: Syntax to call variables

    I assigned my excel file, text file and cmd (batch files) to variables.

    What is the syntax to call these files from within my batch file?
    Do i enclose the variable to %?


    set TxtFile = TextFilename.txt
    set ExcelFile = ExcelFilename.xls
    set CMDFile = BatchFile.cmd

    IF EXIST "%CD%\Folder\%ImportFile%" (
    del "%CD%\Folder\%ImportFile%"

    call %CMDFIle%

    Is this correct?

  2. #2
    Join Date
    Oct 2002
    Baghdad, Iraq
    You're using the variables correctly.

    Consider using Windows Scripting Host. You get a proper scripting language (Visual Basic Script), and can even automate the Excel application from within the script. Some of the problems I mention just don't occur, though there are always ways to shoot yourself in the foot.

    Anyhow, if you're set on using batch files, then cmd /? has a lot of helpful information.

    Here are some tricks for debugging batch files:

    Put "echo" or "rem" in front of commands. Then you can see what it's going to try to do without blowing up your hard drive. I did this with your code:

    C:\test>set TxtFile = TextFilename.txt
    C:\test>set ExcelFile = ExcelFilename.xls
    C:\test>set CMDFile = BatchFile.cmd
    C:\test>IF EXIST "C:\test\Folder\" (echo del "C:\test\Folder\" )
    C:\test>echo call
    You're using the del command. Before you delete anything, you have to validate that it's what you intended to delete. People have lost their jobs over this, so it's a very real danger.

    The ways it can go wrong are:

    1. Variable substitution fails

    set baz = myDirectory
    del /s /q "\%bar%\foo"
    I think Windows would just complain about this, but you don't want to rely on it.

    2. cd fails

    cd d:\somedir
    del /s /q *.*
    Two ways this could go wrong:

    a. cd fails and you're still in d:\anotherDirectory.

    b. cd succeeds, but you're still in c:\ because you forgot to do "c:" by itself.

    Since you're using the %CD% environment variable, you're susceptible to this problem. Try to check that some file (like the script itself) is present before you assume you're in the right directory.

    3. failure to quote

    I noticed that you properly quoted your stuff, so you've got the right idea.

    Again, any language can accidentally wipe a hard drive, but batch languages that use variable substitution have these huge vulnerabilities that other languages don't have. (And they're designed for this sort of thing... go figure.)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts