我的批处理文件循环由于打开文件而停止 [英] My Batch file loop stops because of open file

查看:79
本文介绍了我的批处理文件循环由于打开文件而停止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建批处理文件,以对我们网络上的多个设备执行ping操作,并继续在无限循环中将ping结果数据记录在输出文件中.但是,由于打开了输出文件,因此无限循环被挂起.手动关闭输出文件后,循环将开始另一个迭代并记录更多数据.如何自动执行此步骤?我已经使用taskkill经历了很多选择,但是由于某种原因它们都不会关闭输出文件.其他记事本文件会关闭,但不会在记事本上运行输出文件.

I am trying to build a batch file that pings multiple devices on our network and continues logging ping results data in an output file in an infinite loop. However, the infinite loop gets hung up because the output file is open. Once I manually close the output file, the loop begins another iteration and logs more data. How do I automate this step? I've gone through so many options with taskkill, but none of them will close the output file for some reason. Other Notepad files close, but not the output file running on notepad.

感谢您的帮助!代码如下:

Thanks for you help! Code is below:

@echo off
if exist C:\Users\Tsgadmin\Desktop\data\computers.txt goto Label1
echo.
echo Cannot find C:\Users\Tsgadmin\Desktop\data\computers.txt
echo.
Pause
goto :eof

:Label1
:loop

echo ================================================= >> C:\Users\Tsgadmin\Desktop\ping_firepanels_output.txt
echo PingTest executed on %date% at %time% >> C:\Users\Tsgadmin\Desktop\ping_firepanels_output.txt
for /f %%i in (C:\Users\Tsgadmin\Desktop\data\computers.txt) do call :Sub %%i
notepad C:\Users\Tsgadmin\Desktop\ping_firepanels_output.txt
choice /n/t:c,<10>/c:cc
echo ================================================= >> C:\Users\Tsgadmin\Desktop\ping_firepanels_output.txt
echo. >> C:\Users\Tsgadmin\Desktop\ping_firepanels_output.txt
start notepad.exe
for /f "tokens=2" %%x in ('tasklist ^| findstr notepad.exe') do set PIDTOKILL=%%x
taskkill /F /IM notepad.exe > nul
goto loop
goto :eof

:Sub
echo Testing %1
ping -n 1 %1 >> C:\Users\Tsgadmin\Desktop\ping_firepanels_output.txt | find /i "(0% loss)" 
echo %1 Testing done
echo %1 Testing done >> C:\Users\Tsgadmin\Desktop\ping_firepanels_output.txt

推荐答案

以下是您为该任务重写的批处理代码:

Here is your batch code rewritten for this task:

@echo off
setlocal EnableExtensions DisableDelayedExpansion
set "LogFile=%USERPROFILE%\Desktop\ping_firepanels_output.txt"
set "ListFile=%USERPROFILE%\Desktop\data\computers.txt"

if exist "%ListFile%" goto PrepareForPings
echo/
echo Cannot find file: "%ListFile%"
echo/
endlocal
pause
goto :EOF

rem Delete existing log file before running the echo requests.
rem Get just file name with file extension without path from
rem log file name with path specified at top of the batch file.

:PrepareForPings
del "%LogFile%" 2>nul
for /F %%I in ("%LogFile%") do set "LogFileName=%%~nxI"

rem Always terminate (not kill) running Notepad instance with having
rem the log file opened for viewing before running first/next test run.

:PingLoop
%SystemRoot%\System32\taskkill.exe /FI "WINDOWTITLE eq %LogFileName% - Notepad" >nul 2>nul

echo =================================================>>"%LogFile%"
>>"%LogFile%" echo PingTest executed on %DATE% at %TIME%
echo/>>"%LogFile%"

for /F "usebackq" %%I in ("%ListFile%") do (
    echo Testing %%I ...
    %SystemRoot%\System32\ping.exe -n 1 -w 500 %%I>nul
    if errorlevel 1 (
        echo %%I is not available in network (no reply^).>>"%LogFile%"
    ) else echo %%I is available.>>"%LogFile%"
    echo %%I testing done.
)

echo =================================================>>"%LogFile%"
echo/>>"%LogFile%"

start "" %SystemRoot%\notepad.exe "%LogFile%"
echo/
%SystemRoot%\System32\choice.exe /C NY /N /T 10 /D Y /M "Run again (Y/n): "
echo/
if errorlevel 2 goto PingLoop
endlocal

通常,建议在批处理文件顶部定义多次指定文件名的环境变量,以使将来更容易修改它们.

In general it is advisable to define environment variables with names of files specified multiple times in the batch file at top to make it easier to modify them in future.

在引用这些文件环境变量时,强烈建议将名称用双引号引起来,以在具有路径的文件名包含空格字符或以下字符之一的情况下也获得有效的批处理文件:&()[]{}^=;!'+,`~

On referencing those file environment variables it is strongly recommended to enclose the name in double quotes to get a working batch file also when file name with path contains a space character or one of these characters: &()[]{}^=;!'+,`~

如果在for /F命令行中将用双引号引起来的文件名指定为要读取哪些行的文本文件,则必须使用选项usebackq来将用双引号引起来的文件名解释为file名称,而不是由 FOR 处理的字符串.

If a file name enclosed in double quotes is specified as text file of which lines to read in a for /F command line, it is necessary to use option usebackq to get interpreted the file name enclosed in double quotes as file name and not as string to process by FOR.

DosTips论坛主题 ECHO.不能输入文本或空白行-而是使用ECHO/解释为什么最好使用echo/而不是echo.输出空行.

The DosTips forum topic ECHO. FAILS to give text or blank line - Instead use ECHO/ explains why it is better to use echo/ instead of echo. to output an empty line.

用于发送 Notepad 的终止信号的 TASKKILL 命令应仅发送到具有日志文件的 Notepad 实例打开并且没有其他可能正在运行的记事本实例.

The TASKKILL command used to send Notepad the terminate signal for a graceful termination should be send only to the Notepad instance having the log file opened and not any other perhaps running Notepad instance.

>>>重定向到文件的 ECHO 行,其中还有一个空格留给重定向操作符,导致该空间也作为尾随空格写入文件中.因此,要写入文件的文本和重定向运算符之间应该没有空格. >>>的空格权限不会出现问题,因为它不会写入文件中.

An ECHO line redirected to a file with > or >> with a space left to redirection operator results in having this space also written as trailing space into the file. For that reason there should be no space between text to write into the file and redirection operator. A space right to > or >> would be no problem as not written into the file.

ECHO 行上输出的可变文本重定向到可能以123,... 9结尾的文件时,有必要在行首以>>指定从 STDOUT 到文件的重定向,否则1>>2>>,...在执行 ECHO 命令行.另请阅读有关使用命令重定向操作符的Microsoft文章.

When a variable text is output on an ECHO line redirected into a file which could end with 1, 2, 3, ... 9, it is necessary to specify the redirection from STDOUT into the file with >> at beginning of the line as otherwise 1>>, 2>>, ... would be interpreted different as expected on execution of the ECHO command line. Read also the Microsoft article about Using Command Redirection Operators.

此任务没有必要的子例程.也可以在此处使用以圆括号(开头并匹配)的命令块.这样可以使循环的执行速度更快,但实际上并没有明显更快,但是仍然更快.

There is no subroutine necessary for this task. A command block starting with opening parenthesis ( and matching ) can be used here too. That makes the execution of the loop a bit faster, not really noticeable faster, but nevertheless faster.

在日志文件中有一个用echo编写的文本,该文本还包含一个右括号),该括号不在双引号引起来的字符串中.此)将被解释为与)匹配,以打开 IF 条件的真实分支的(.必须使用转义字符^来转义),以使Windows命令解释器将)解释为文字字符.

There is a text written with echo into the log file containing also a closing parenthesis ) not within a double quoted string. This ) would be interpreted as matching ) for opening ( of true branch of IF condition. It is necessary to escape ) with caret character ^ to get ) interpreted as literal character by Windows command interpreter.

PING 会以退出代码1退出.否则,在成功回复后,退出代码为0.通过errorlevel评估退出代码比过滤与语言相关的输出要好.

PING exits with exit code 1 if the echo request was not replied. Otherwise on successful reply the exit code is 0. It is better to evaluate the exit code via errorlevel than filtering the language dependent output.

具有要查看的日志文件的记事本的新实例,以运行 Notepad 执行批处理文件.否则,只要用户未关闭启动的 Notepad 实例,该批处理文件的执行就会停止.在命令行中从记事本开始删除start ""时,很容易看到不同的行为.

New instance of Notepad with the log file to view is started by this batch file using command start to run Notepad in a separate process running parallel to command process executing the batch file. Otherwise the execution of the batch file would be halted as long as the started Notepad instance is not closed by the user. That different behavior can be easily seen on removing start "" at beginning of the command line starting Notepad.

命令 CHOICE 使批处理文件的用户可以在10秒内按 N 键(不区分大小写)退出循环.否则,用户提示会自动以选项Y答复,并通过首先终止运行记事本再次执行循环.

The command CHOICE gives the user of the batch file the possibility to exit the loop by pressing key N (case-insensitive) within 10 seconds. Otherwise the user prompt is automatically answered with choice Y and the loop is executed once again by first terminating running Notepad.

要了解所使用的命令及其工作方式,请打开命令提示符窗口,在其中执行以下命令,并非常仔细地阅读每个命令显示的所有帮助页面.

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

  • choice /?
  • del /?
  • echo /?
  • endlocal /?
  • for /?
  • goto /?
  • if /?
  • pause /?
  • ping /?
  • set /?
  • setlocal /?
  • start /?
  • taskkill /?
  • choice /?
  • del /?
  • echo /?
  • endlocal /?
  • for /?
  • goto /?
  • if /?
  • pause /?
  • ping /?
  • set /?
  • setlocal /?
  • start /?
  • taskkill /?

另请参阅 Windows环境变量,以获取有关环境变量USERPROFILESystemRoot在此批处理文件中使用.

See also Windows Environment Variables for details on environment variables USERPROFILE and SystemRoot as used in this batch file.

这篇关于我的批处理文件循环由于打开文件而停止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆