这个脚本做什么(Windows CMD)

时间:2017-11-12 23:33:47

标签: windows cmd

SET /P A=SPR
IF /I "%A:~,1%" EQU "d" ( 
    IF EXIST %1 ( 
        IF NOT EXIST %2 ( 
            COPY %1 %2 
        )
    )
)

1 个答案:

答案 0 :(得分:1)

First, I suggest to open a command prompt window and run the following commands:

  • set /?
  • if /?
  • copy /?
  • call /? ... explains %1 and %2.

For each command the help is output which you should read from top to bottom.

This small batch file first prompts the batch file user for a string with prompt text SPR. The string entered by the user is assigned to environment variable A if the user enters anything at all as expected by this batch file.

Next a case-insensitive string comparison is done to check if the first character of the string entered by the user is d or D.

It would be much better to use comparison operator == instead of EQU in this case. == always makes a string comparison while EQU first tries to compare integers and if that fails because it is not possible to convert both comparison arguments to signed 32-bit integers, a string comparison is done. The second argument d is not a signed 32-bit integer.

The batch file must be started with two arguments being in this case two file names without or with wildcards. I suppose the batch file expects two file names without or with path without wildcards.

If the first condition is true, the batch file checks next if source file with name passed to batch file as first argument exists and next if target file passed to batch file as second argument does not exist. The source file is copied to target file if those 2 conditions are true.

More fail safe would be:

SET "Input=?"
SET /P "Input=SPR: "
IF /I "%Input:~0,1%" == "d" (
    IF "%~1" == "" GOTO :EOF
    IF "%~2" == "" GOTO :EOF
    IF EXIST "%~1" IF NOT EXIST "%~2" COPY "%~1" "%~2"
)

The environment variable Input is now predefined with ? as string. So when the user just hits RETURN or ENTER without entering anything at all, the environment variable Input is nevertheless defined with ? as string and next command IF works, but of course the condition is in this case false.

The IF condition as is results in an exit of batch execution because of an syntax error only when the first entered character is ". In all other cases the IF condition works now and runs a case-insensitive string comparison.

The improved batch file checks next if the batch file was really started with two argument strings as expected and exit the batch file with a jump to predefined label for End Of File if either first or second argument is an empty string (or a string consisting only of one or two double quotes).