Home > Enterprise >  Pinging Hostnames from a Parsed File and Logging in Batch
Pinging Hostnames from a Parsed File and Logging in Batch

Time:08-02

I'm still pretty new to batch but I wanted to try out some different functionalities within the same batch program. Essentially, I am attempting to parse through a .txt file of hostnames and ping them 1 time each, and return a pass or fail by utilizing a find query for the specific ping result. The second find query is redundant but left in. A string of "timed out" indicates that the host is down. I have been able to achieve this with this bulky code, but my actual ping statistics are no longer being written to this log file.

I'm not too familiar with the command pipeline character but it may just be incompatible for this specific use case. If I remove the piped command for the find query, it is able to write the output of the ping command just fine, but then I lose the utility of a return pass or fail value. Is this just a simple syntax error? I've tried moving the location of the actual write to file argument on the line itself but it hasn't worked. Also, why are the errorlevel values inverted (line 21)? I can't seem to return what I'm looking for.

Is there anyway I can get all these parts to play nice together? I apologize if the answer is quite obvious...

@echo off
  
setlocal   

set hosts=temp.txt
set count=0    

echo.
echo Parsing File: %hosts%
echo.

echo Start > C:\Users\___\Downloads\pingLOG.txt

for /F "tokens=*" %%i in (%hosts%) do (
    set /A count=count 1
    echo 
    echo.
    echo [ ] Pinging: %%i
    echo [ ] Pinging: %%i >> C:\Users\___\Downloads\pingLOG.txt
    echo.
    ping -n 1 "%%i" | find /I "timed out" >> C:\Users\___\Downloads\pingLOG.txt
    if errorlevel == 1 (
        echo Pass
    ) else (
    echo Fail
    )

    echo.
    echo %TIME% >> C:\Users\___\Downloads\pingLOG.txt
)
echo.
echo %count%  Hosts Scanned
find /c "timed out" C:\Users\___\Downloads\pingLOG.txt
echo.
pause

CodePudding user response:

You can't filter the output for a certain string and expect the complete output (eliminating unwanted parts is the very reason for filtering).
To accomplish your goal, you need a temporary file (the complete output) and filter that file, so you have both variants (filtered and unfiltered) (suboptimal, but well...):

ping -n 1 "%%i" >"%temp%\temp.tmp"
find /I "timed out" "%temp%\temp.tmp" >nul && set "status=Fail" || set "status=Pass"
type "%temp%\temp.tmp" >> "C:\Users\___\Downloads\pingLOG.txt"
echo %status% >> "C:\Users\___\Downloads\pingLOG.txt"
  • Related