![El uso de 'ping' y 'findstr' en un bucle 'for' de un archivo por lotes primero arroja un error, no un comando externo interno, pero nuevamente muestra el resultado](https://rvso.com/image/1671509/El%20uso%20de%20'ping'%20y%20'findstr'%20en%20un%20bucle%20'for'%20de%20un%20archivo%20por%20lotes%20primero%20arroja%20un%20error%2C%20no%20un%20comando%20externo%20interno%2C%20pero%20nuevamente%20muestra%20el%20resultado.png)
Este archivo por lotes
@echo off
set path=C:\Users\ssiyengar\Desktop\Pingtest\pinglist.csv
set file=C:\Users\ssiyengar\Desktop\Pingtest\temp.txt
set qosping=1
cls
for /f "tokens=1-3 delims=," %%a IN (%path%) do (
ping %%c -n %qosping% > %file%
findstr "time< time=" %file% >nul
if %errorlevel%==1 (
echo %%a %%b IP %%c Ping FAILURE
) else (
echo %%a %%b IP %%c Ping SUCCESS
)
)
pause
salidas:
'ping' is not recognized as an internal or external command,
operable program or batch file.
'findstr' is not recognized as an internal or external command,
operable program or batch file.
SYS1 MC1 IP XX.XX.XX.XX Ping SUCCESS
El archivo CSV es:
SYS1,MC1,IP1 \
SYS2,MC2,IP2
¿Por qué hace ping/encontrartr¿no reconocido?
Si paso los valores directamente en lugar del archivo CSV, funciona bien. ¿Por qué? ¿Cómo puedo resolverlo?
Nota: Las variables de entorno ya contienen la ruta de Sys32
.
Respuesta1
El problema es que tú marcas el camino. Path es una variable ambiental especial diseñada para contener rutas a ubicaciones que tienen programas, como ping y findtr.
al escribir set path=... sobrescribes esta lista con un archivo que borra la ruta durante este tiempo de ejecución. Afortunadamente, usar set solo cambia la variable durante el tiempo de ejecución de este script y no para todas las sesiones. Es por eso que ir a cmd y escribir ping con los valores del csv sigue funcionando.
Si escribe la línea set path= en esa misma sesión de cmd, el ping de escritura manual con los valores tampoco funcionará hasta que cmd se cierre y se vuelva a abrir.
Si cambia: set path=
hacia set mypath=
y %path%
hacia %mypath%
su script funcionará.
Respuesta2
En elvariables del sistemaya tienes una variable con el nombre ruta,
apunta a varias rutas donde se encuentra el intérprete de comandos (cmd.exe)
buscará y ejecutará sus comandos, buscando archivos con las extensiones
definidas enRutaExt, y al no encontrarlo, te devolverá:
- 'ping' no se reconoce como un comando interno o externo, programa ejecutable o archivo por lotes.
- 'findstr' no se reconoce como un comando interno o externo, programa ejecutable o archivo por lotes.
Le sugiero que conozca los nombres de las variables y comience a usar nombres diferentes.
Respuesta3
Puedes intentarlo así y tampoco necesitas crear un archivo temporal:
@echo off
Title Ping Tester
set "My_CSV_PingList=%~dp0pinglist.csv"
set qosping=1
set "LogFile=%~dp0PingResults.txt"
If exist "%LogFile%" Del "%LogFile%"
cls
SetLocal EnableDelayedExpansion
for /f "tokens=1-3 delims=," %%a IN (%My_CSV_PingList%) do (
Ping -n %qosping% %%c |find "TTL=">nul) && (
set "msg=%%a %%b IP %%c Ping SUCCESS" && echo !msg!
echo !msg!>>"%LogFile%"
) || (
set "msg=%%a %%b IP %%c Ping FAILURE" && echo !msg!
echo !msg!>>"%LogFile%"
)
)
EndLocal
Start "Log" /MAX "%LogFile%"
pause
Prima:Consulte cómo utilizarvarios colores en lote. Puedes mostrar el mensaje con un color verde cuandoéxitoy un color rojo cuandofalla.
@echo off
Title Ping Tester With Powershell Foreground Colors In A Batch File
set "My_CSV_PingList=%~dp0pinglist.csv"
set qosping=1
set "LogFile=%~dp0PingResults.txt"
If exist "%LogFile%" Del "%LogFile%"
cls
SetLocal EnableDelayedExpansion
for /f "tokens=1-3 delims=," %%a IN (%My_CSV_PingList%) do (
Ping -n %qosping% %%c |find "TTL=">nul) && (
set "msg=%%a %%b IP %%c Ping SUCCESS" && Call :PSColor "!msg!" Green \n
echo !msg!>>"%LogFile%"
) || (
set "msg=%%a %%b IP %%c Ping FAILURE" && Call :PSColor "!msg!" Red \n
echo !msg!>>"%LogFile%"
)
)
EndLocal
Start "Log" /MAX "%LogFile%"
pause
Exit /B
::---------------------------------------------------------------
:PSColor <String> <Color> <NewLine>
If /I [%3] EQU [\n] (
Powershell Write-Host "`0%~1" -ForegroundColor %2
) Else (
Powershell Write-Host "`0%~1" -ForegroundColor %2 -NoNewLine
)
Exit /B
::--------------------------------------------------------------
Respuesta4
Deje de usar el símbolo del sistema anticuado y use PowerShell en su lugar.
$hosts = Import-CSV pinglist.csv
$hosts | Foreach-Object {
$result = (Test-NetConnection -ErrorAction SilentlyContinue `
-WarningAction SilentlyContinue -InformationLevel Quiet $_.IP) ? "SUCCESS" : "FAILURE"
Write-Host ("{0} {1} IP {2} {3}" -f $_.Name,$_.mc,$_.IP,$result)
}
Debe agregar una línea de encabezado a su CSV para obtener los nombres de los atributos por línea:
Name,mc,IP