سؤال

Consider following simple script

for /f "delims=" %%a in ('dir') do echo %%a

save as a.bat, then run.

It works perfect on my home pc (win7 x64), printing files under current directory, but getting "The syntax of the command is incorrect" on my office machine (also win7 x64).

Don't have a clue why this happens, but it's quite annoying I can't install some software because of this.

It's been verified that "run as administrator" doesn't help.

Did I do something wrong to my office machine which corrupt batch command parsing..

هل كانت مفيدة؟

المحلول 2

Finally get it working.

The problem comes from environment variable %COMSPEC%.

Don't know why it's changed from "C:\windows\systems32\cmd.exe" to "C:/windoes/systems32/cmd.exe", The forward slash screw things up.

No idea why this matters, but seems that back slash is safer under windows:-)

نصائح أخرى

Do you really use command dir in your batch file or another command, a command which itself is enclosed in double quotes because of a space in path or has a parameter in double quotes?

If the output of a command should be processed within the loop and the command itself must be specified in double quotes or at least one of its parameters, the following syntax using back quotes is required:

for /f "usebackq delims=" %%a in (`"command to run" "command parameter"`) do echo %%a

An example:

for /f "usebackq delims=" %%a in (`dir "%CommonProgramFiles%"`) do echo %%a

%CommonProgramFiles% references the value of environment variable CommonProgramFiles which is a directory path containing usually spaces. Therefore it is necessary to enclose the parameter of command dir in double quotes which requires the usage of usebackq and back quotes after the opening and before the closing round bracket.

Further I suggest to look on value of environment variable PATH. There are applications which add their program files directory to PATH during installation, but not by appending the directory to end of the list of directories, but by inserting them at beginning. That is of course a bad behavior of the installer of those applications.

If you call in your batch file standard Windows commands not located in cmd.exe, but in Windows system directory which is usually the first directory in PATH, like the command find, and the installed application by chance has also an executable with same name in the program files directory of the application, the batch file might not work on this computer because of running the wrong command.

It is safer to use instead of just find in a batch file %SystemRoot%\system32\find.exe to avoid problems caused by bad written installer scripts of applications modifying the PATH list on wrong end.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top