批处理文件输入验证整数

时间:2014-04-03 02:48:00

标签: batch-file

我想告诉用户在关闭计算机之前输入他想要多少分钟,我不知道如何避免用户输入中的任何字母。我只是想允许一个数字去完成

@ECHO OFF

pushd %systemroot%
echo *{Enter the number of minutes  required before Turn off the computer then press (enter)}
set/p "x="


if %x% EQU %x% set/a z= 60*%x%
echo %z%
shutdown -s -t %z%


echo finish

2 个答案:

答案 0 :(得分:1)

@ECHO OFF
SETLOCAL

pushd %systemroot%
echo *{Enter the number of minutes  required before Turn off the computer then press (enter)}
set/p "x="

SET "notnumber=9%x%"
FOR /l %%z IN (0,1,9) DO CALL SET "notnumber=%%notnumber:%%z=%%"
IF DEFINED notnumber ECHO entry was NOT a number&GOTO :EOF 

set/a z= 60*%x% 2>NUL
IF ERRORLEVEL 1 ECHO invalid number entered&GOTO :EOF 
echo %z%
ECHO shutdown -s -t %z%


echo finish
GOTO :eof

请注意,批处理将以0开头的数字视为OCTAL,因此输入09无效(因为它不是八进制)并且输入013有效,但会超时11分钟,因为13八进制是11十进制。

另请注意,shutdown命令只是echo以避免在测试期间关闭。

答案 1 :(得分:1)

这是另一种方法:

@ECHO OFF
pushd "%systemroot%"
:loop
"set x="
set /p "x=Enter the number of minutes required before Turn off the computer then press (enter) "
rem this allows the user to press enter to quit without doing anything
if not defined x goto :EOF
rem check for numerals only - else loop to start again
set "num="
for /f "delims=0123456789" %%a in ("%x%") do set "num=%%a"
if defined num goto :loop

set /a z=60*%x%
echo %z%
shutdown -s -t %z%

echo finish