0

I am writing a batch file for some work where I need to check if the hosts are reachable or not. I need to log all the error codes I receive on execution of the commands I perform.

Specifically, I need to use ping, traceroute and arp command. But I do not find various error levels for executing these commands. Where can I find error levels or error codes for such windows commands ?

Also, is it better to use pathping instead of ping and traceroute separately?

1 Answer 1

1

Batch solution with %ERRORLEVEL%

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

:Logit
:: PING 192.168.1.1 -n 1 | FIND /I /V "unreachable" | FIND /I "Reply from "

It basically redirects the output of the :Logit method to the LOGFILE. The exit command is to ensure the batch exits after executing :Logit.


Here's a PowerShell solution with a simple try-catch

Try {
    # Try to reach host 
    Test-Connection -Source "Server02", "Server12", "localhost" -ComputerName "Server01"    
}

Catch {

    # Catch the exception

    $_ | Out-File C:\errors.txt -Append

    # You can use this too but not both

    $exception = $_.Exception.Message
    Out-File -FilePath 'C:\myscript.log' -Append -InputObject $exception
}

From this and this SO questions.


PowerShell

Microsoft doc about Test-Connection

Error handling in PowerShell

5
  • I am looking for batch file, not powershell. Apr 3, 2018 at 7:00
  • Both of batch and ps1 are Windows native, can you specify your environment?
    – Didix
    Apr 3, 2018 at 8:18
  • I need to use batch. Apr 3, 2018 at 8:51
  • Thank you for editing the answer, but I do not ask for code. I am asking where can I find the possible errors for such windows commands? Let it be with powershell's Test-Connection or Batch's Ping. Apr 4, 2018 at 4:14
  • @tech_enthusiast It should be store in errorlevel or %ERRORLEVEL% if he can't find errorlevel about %ERRORLEVEL%
    – Didix
    Apr 4, 2018 at 6:11

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .