下面是我的批处理脚本。我保存了扩展名为 file.bat 的文件,然后双击它。它没有显示任何内容,因为文件路径包含空格(在 中set file="C:\SUPPORT\APAC SIT\NewtextDoc.txt"
)
如果我使用set file="C:\SUPPORT\APACSIT\NewtextDoc.txt"
,它就起作用。
如果我使用set file="C:\SUPPORT\APAC SIT\NewtextDoc.txt"
,它就不起作用。
@ECHO OFF
REM The below command will look for the size of file on the server and
inform the user if scheduler is down.
setlocal
set nl=^& echo.
set file="C:\SUPPORT\APAC SIT\NewtextDoc.txt"
set maxbytesize=0
FOR /F "usebackq" %%A IN ('%file%') DO set size=%%~zA
if %size% EQU %maxbytesize% (echo WARNING !!! %nl%Scheduler File is ^=
%maxbytesize% bytes%nl%Please do not process invoices, contact Webcenter
Support) else (echo Scheduler File OK)
PAUSE
答案1
- 包含以下项的转义字符串
cmd
有毒人物在变量中使用双引号定义变量时:set "_nl=& echo."
set "_file=path with spaces\name.ext"
- (只有在极少数情况下才需要另一种转义模式)
- 进而以适当的方式使用变量:
- 未转义:
echo WARNING !!!%_nl%Scheduler File is ^=%_size% bytes
- 逃脱:
FOR /F "usebackq delims=" %%A IN ('"%_file%"') DO set "_size=%%~zA"
- 未转义:
请注意,下一个脚本中定义的变量名以_
低线(下划线)为前缀,以便于调试,请参阅SET _&PAUSE
调试(临时)输出。
注释脚本:
@ECHO OFF
SETLOCAL EnableExtensions DisableDelayedExpansion
REM The below command will look for the size of file on the server
REM and inform the user if scheduler is down.
set "_nl=& echo." escape ampersand by double quotes
set "_file=D:\bat\odds and ends\a b\testfile.txt" escape spaces using double quotes
rem set "_file=C:\SUPPORT\APAC SIT\NewtextDoc.txt"
set "_maxbytesize=0" keep using double quotes even if unnecessary
if not exist "%_file%" (
set /A "_size=_maxbytesize-1"
echo "%_file%" does not exist
) else (
FOR /F "usebackq delims=" %%A IN ('"%_file%"') DO set "_size=%%~zA"
)
echo debugging output should show variables _file, _maxbytesize, _nl, _size
SET _&PAUSE
if %_size% LEQ %_maxbytesize% (
echo WARNING !!!%_nl%Scheduler File is ^=%_size% bytes
echo Please do not process invoices, contact Webcenter Support
) else (
echo Scheduler File OK%_nl%"%_file%" filesize is %_size% bytes
)
PAUSE
输出:
==> rename "D:\bat\odds and ends\a b\testfile.txt" testfilea.txt
==> set _
Environment variable _ not defined
==> D:\bat\SU\1130895.bat
"D:\bat\odds and ends\a b\testfile.txt" does not exist
debugging output should show variables _file, _maxbytesize, _nl, _size
_file=D:\bat\odds and ends\a b\testfile.txt
_maxbytesize=0
_nl=& echo.
_size=-1
Press any key to continue . . .
WARNING !!!
Scheduler File is =-1 bytes
Please do not process invoices, contact Webcenter Support
Press any key to continue . . .
==> rename "D:\bat\odds and ends\a b\testfilea.txt" testfile.txt
==> D:\bat\SU\1130895.bat
debugging output should show variables _file, _maxbytesize, _nl, _size
_file=D:\bat\odds and ends\a b\testfile.txt
_maxbytesize=0
_nl=& echo.
_size=13
Press any key to continue . . .
Scheduler File OK
"D:\bat\odds and ends\a b\testfile.txt" filesize is 13 bytes
Press any key to continue . . .
==>