2

I got this command below.

@echo off

pushd %~dp0
echo "checking unhealthy cmclient" >> %~dp0\pc_down_info.txt
for /F  %%M  in  (%~dp0\pc_info.txt) do (
        ping -n 1 -w 1 %%M >nul
        if errorlevel 1 echo %%M is down >> %~dp0\pc_down_info.txt
        If not errorlevel 1 (
                cd c:\psexec
                psexec -d -i \\%%M %~dp0\FixCM.exe 
            )
    )
pause

I'll try to execute a file remotely using psexec. I got the list of PC's in pc_info.txt. And Im trying to execute FixCM.exe which is in a shared drive. But it prompts "Syntax command is incorrect". Whats wrong with my code?

Regie Baguio
  • 241
  • 5
  • 13
  • 2
    You only use a leading percent symbol to reference the command line arguments. `%~dp0` – Squashman Mar 03 '17 at 14:51
  • 2
    Also, `(` needs to be on the same line as the `for` (and the `if`). – SomethingDark Mar 03 '17 at 14:53
  • Have edited my code above, another error prompt "`psexec` is not recognized as an internal or external command", so frustrating. – Regie Baguio Mar 03 '17 at 15:19
  • 1
    Are you sure there is a directory named `psexec` at the root of `C:` including an executable file named `psexec` with an extension as defined in `%pathext%`? If so it may be something as simple as `%~dp0` being a different drive, and you'd need to change `cd c:\psexec` to `cd /d c:\psexec` or another executable file existing which has the name `psexec` with another extension as defined in `%pathext%`. – Compo Mar 03 '17 at 15:29
  • 1
    If your batch file is located in a different drive letter, your `CD` command needs to use the `/D` option. Regardless of that why not just specify the full path to psexec when you execute it. Otherwise you are doing a whole bunch of CD commands that don't need to be done. – Squashman Mar 03 '17 at 15:38
  • Is _"Syntax is incorect"_ phrase redundant or recursive? **`;)`** – Aacini Mar 04 '17 at 19:24

1 Answers1

1

Here's a quick rewrite, hopefuly covering all of the comments raised so far.

@Echo Off
Echo="checking unhealthy cmclient">>"%~dp0pc_down_info.txt"
For /F "UseBackQ" %%M In ("%~dp0pc_info.txt") Do (
    ("%__AppDir__%Ping.exe" -n 1 -w 1 %%M)>Nul 2>&1
    If ErrorLevel 1 (Echo=%%M is down>>"%~dp0pc_down_info.txt") Else (
        "C:\PsExec\PsExec.exe" -d -i \\%%M "%~dp0FixCM.exe"))
Pause

You will note I have placed paths inside doublequotes, because it is good practice and I have no idea if the script directory contains characters, such as spaces, which would cause problems without them.

Compo
  • 36,585
  • 5
  • 27
  • 39
  • I just reviewed the code, what does this characters do? `2>&1` ? Do I really need to put these to avoid errors? – Regie Baguio Mar 24 '17 at 10:11
  • It doesn't avoid errors, just redirects the standard and error outputs to a null device. As we only need to know the ErrorLevel these potential messages are superfluous. – Compo Mar 24 '17 at 17:37