脚本1:
输入(“删除Quotes.cmd”“这是测试”)
@ECHO OFF
REM Set "string" variable to "first" command line parameter
SET STRING=%1
REM Remove Quotes [Only Remove Quotes if NOT Null]
IF DEFINED STRING SET STRING=%STRING:"=%
REM IF %1 [or String] is NULL GOTO MyLabel
IF NOT DEFINED STRING GOTO MyLabel
REM OR IF "." equals "." GOTO MyLabel
IF "%STRING%." == "." GOTO MyLabel
REM GOTO End of File
GOTO :EOF
:MyLabel
ECHO Welcome!
PAUSE
输出(没有,%1不是空白,空或NULL):
使用以上脚本1运行(“ Remove Quotes.cmd”),不带任何参数
输出(%1为空白,空或NULL):
Welcome!
Press any key to continue . . .
注意:如果您在IF ( ) ELSE ( )
语句中设置了变量,则在退出“ IF”语句后,DEFINED才可用该变量(除非启用了“延迟变量扩展”;启用后,请使用感叹号“!”代替百分比“%”符号}。
例如:
脚本2:
输入(“删除Quotes.cmd”“这是测试”)
@ECHO OFF
SETLOCAL EnableDelayedExpansion
SET STRING=%0
IF 1==1 (
SET STRING=%1
ECHO String in IF Statement='%STRING%'
ECHO String in IF Statement [delayed expansion]='!STRING!'
)
ECHO String out of IF Statement='%STRING%'
REM Remove Quotes [Only Remove Quotes if NOT Null]
IF DEFINED STRING SET STRING=%STRING:"=%
ECHO String without Quotes=%STRING%
REM IF %1 is NULL GOTO MyLabel
IF NOT DEFINED STRING GOTO MyLabel
REM GOTO End of File
GOTO :EOF
:MyLabel
ECHO Welcome!
ENDLOCAL
PAUSE
输出:
C:\Users\Test>"C:\Users\Test\Documents\Batch Files\Remove Quotes.cmd" "This is a Test"
String in IF Statement='"C:\Users\Test\Documents\Batch Files\Remove Quotes.cmd"'
String in IF Statement [delayed expansion]='"This is a Test"'
String out of IF Statement='"This is a Test"'
String without Quotes=This is a Test
C:\Users\Test>
注意:它还将从字符串内部删除引号。
例如(使用脚本1或2):C:\ Users \ Test \ Documents \ Batch Files>“删除Quotes.cmd”“这是” a“测试”
输出(脚本2):
String in IF Statement='"C:\Users\Test\Documents\Batch Files\Remove Quotes.cmd"'
String in IF Statement [delayed expansion]='"This is "a" Test"'
String out of IF Statement='"This is "a" Test"'
String without Quotes=This is a Test
在脚本2中不带任何参数的情况下执行(“ Remove Quotes.cmd”)。
输出:
Welcome!
Press any key to continue . . .
if "%1" == "" GOTO MyLabel
只要%1
双引号的偶数都不会致命地终止脚本的执行。我看到一个奇数的双引号%1
终止了该脚本的执行,并出现以下错误:The syntax of the command is incorrect.
使用方括号解决问题的以下解决方案已被标记为正确答案,但似乎并没有做得更好。当%1
双引号的数量为奇数时,该解决方案也会因相同的错误而失败。