Search code examples
batch-filefor-loopfindstrnetstattaskkill

Error "| was unexpected at this time."


I am using code as below to delete program using port 8080, but I got error | was unexpected at this time., what can I do?

FOR /F "tokens=5 delims= " %P IN ('netstat -a -n -o | findstr :8080') DO TaskKill.exe /PID %P

Solution

  • The condition inside the for must be parsed by the batch parser before it can pass it to the IN() clause as an executable command. To preserve special characters like <, >, &, |, ^, or %, you have to escape them in the script. The escape character in Batch is "^".

    Escape the vertical bar with a caret:

    FOR /F "tokens=5 delims= " %P IN ('netstat -a -n -o ^| findstr :8080') DO TaskKill.exe /PID %P
    

    I might also add that when saved as a .bat, the percent characters have to be escaped as well. Instead of "%P", you would need to use "%%P".