1

I'm trying to create a little batch file that checks multiple PCs read from a text file. For any PCs it finds are pingable, it writes a line in a "results" text file saying so. Here's what I've got:

@Echo off
set file=C:\logs\registercheck.txt
date /t >%file%
FOR /F %%I IN (C:\work\regnames.txt) DO (ping /n 1 %%I | ping /n 1 %%I | IF errorlevel 1 goto :nextreg | echo %%I is still on and has not been powered off! >>%file% | :nextreg)
PAUSE  

So...when I run the file, I get multiple lines of "goto was unexpected at this time" and the only thing written in my output text file is the date. What am I doing wrong?

Thank you!

1 Answers1

2
@Echo off
    setlocal enableextensions disabledelayedexpansion

    set "logFile=C:\logs\registercheck.txt"
    set "inputFile=C:\work\regnames.txt"

    >>"%logFile%" date /t

    for /f "usebackq delims=" %%i in ("%inputFile%") do (
        ping -n 1 %%i >nul 2>nul 
        if not errorlevel 1 (
            >>"%logFile%" echo(%%i is still on and has not been powered off! 
        )
    )

You have two errors.

The first is that to put all the commands in a single line, the separator is not the pipe character (|) but the ampersand (&)

The second is that inside the do code block of the for command, if one goto is executed, the for command is finished, independently of where the label is placed. And labels inside for code blocks usually generate errors (depends of its position).

If instead of the previous code, you want a single line loop, it can be written as

for /f "usebackq delims=" %%i in ("%inputFile%") do ( ping -n 1 %%i >nul 2>nul & if not errorlevel 1 >>"%logFile%" echo(%%i is still on and has not been powered off! )

or

for /f "usebackq delims=" %%i in ("%inputFile%") do ( ping -n 1 %%i >nul 2>nul && >>"%logFile%" echo(%%i is still on and has not been powered off! )

that makes use of the && construct. It is intended as a shortcut for the if not errorlevel 1 .... If the command at the left of the && does not raise an errorlevel, then the command on the right side is executed.

This for the batch sintax. Now the ping. There is a difference in how ping command behaves depending of the ip version. It is not the same to ping an ipv4 address than to ping an ipv6 address. If needed you can grab from here a subrotine to handle the differences.

Community
  • 1
  • 1
MC ND
  • 69,615
  • 8
  • 84
  • 126