web-dev-qa-db-ja.com

IPアドレスにpingを実行し、結果をtxtファイルに保存します。

IPアドレスのリストを開いてpingを実行し、応答をTXTファイルに保存しようとしています。pingはループして問題なく実行され、正しく報告されますが、取得できます。結果をテキストファイルに保存します。

@echo off

SET LOGFILE=MyLogFile.log
call :Logit >> %LOGFILE% 
exit /b 0

for /f "delims=" %%a in ( ' type "C:\Users\kelly\Desktop\Ping\computerlist.txt" ' ) do ping -n 1 %%a >nul && (echo %%a ok >> %LOGFILE% ) || (echo %%a failed to respond >> %LOGFILE% ) 
pause
2
Kelly
@echo off
SET LOGFILE=C:\Temp\MyLogFile.log
SET PINGLIST=C:\Users\kelly\Desktop\Ping\computerlist.txt
for /f "delims=" %%a in (%PINGLIST%) DO ping -n 1 %%a > nul && (echo %%a is ok >> %LOGFILE%) || (echo %%a is unreachable! >> %LOGFILE%)

コンピュータリストの各行にホスト名が1つだけあることを確認してください。

入力(computerlist.txt)

gooobler
google.com
msn.com
localhost

出力(MyLogFile.log)

gooobler is unreachable! 
google.com is ok 
msn.com is unreachable! 
localhost is ok 
1
sippybear

あなたがいるところdo ping -n 1 %%a >nul

これは、ping出力を取得して破棄します。

あなたが欲しいと思う

do ping -n 1 %%a >%LOGFILE%

また、存在しないリージョン/サブルーチン(Logit)を呼び出している

@echo off

SET LOGFILE=MyLogFile.log
call :Logit >> %LOGFILE% 
exit /b 0

:Logit
for /f "delims=" %%a in ( ' type "C:\Users\kelly\Desktop\Ping\computerlist.txt" ' ) do ping -n 1 %%a >nul && (echo %%a ok >> %LOGFILE% ) || (echo %%a failed to respond >> %LOGFILE% ) 
pause

(未テスト)

~~ OPのコメントに基づいて編集し、現在テスト済みです~~

私はこれがあなたが探しているものだと思います:

@ECHO OFF
SET LOGFILE=logFile.txt
SET TEMP_FILE=temp.txt
SET PINGLIST=comps.txt


REM contatenate log file
echo. > %LOGFILE%

for /f "delims=" %%a in (%PINGLIST%) do (
    REM do ping and store response - using a temp file because we care about the response more than once.
    ping -n 1 %%a > %TEMP_FILE%

    REM append response to log file
    type %TEMP_FILE% >> %LOGFILE%

    REM from: https://stackoverflow.com/a/8531199
    REM check if ping determined the Host is unreachable by searching the output
    findstr /c:"Destination Host unreachable" /c:"could not find Host" %TEMP_FILE% > NUL

    REM if the errorlevel is at least 1 (unsuccessful at finding string)
    if errorlevel 1 (
        REM then must have reached Host
        echo %%a is ok >> %LOGFILE%
    ) ELSE (
        REM else, we found the string that sais we cannot reach the Host
        echo %%a is UNREACHABLE^! >> %LOGFILE%
    )
    REM cleanup
    del %TEMP_FILE%
)
exit /b
0
mshafer