1

My batch file is throwing error when run, but when I run the commands one by one manually in command line then I get no error. Here's the batch file 'test.bat'.

echo "test"
cd "c:\packages"
pause
for /R c:\packages %F in (*.msi) do set /A servername=%~nxF
pause
echo %servername%
pause

I get this error - "~nxF was unexpcted at this time".

I got the sample code from https://stackoverflow.com/a/1100466/1105556 I'm just trying the get the file name in c:\packages & store the value in 'servername' variable. There is only one file (.msi) in the folder I cant figure out whats wrong. Can someone please solve the riddle for me?

Community
  • 1
  • 1
Sudhakar
  • 2,904
  • 8
  • 33
  • 47

1 Answers1

4

You need to double the %% in batch files:

for /R c:\packages %%F in (*.msi) do set /A servername=%%~nxF
Ken White
  • 123,280
  • 14
  • 225
  • 444
  • 1
    Also, `set /A` evaluates the RHS as an arithmetic expression, which probably isn't wanted. – arx Jan 28 '12 at 13:40
  • Thank you Ken & @arx. Took both suggestions & it worked. Just out of curiosity what is RHS. I googled it but couldn't find any thing relevant – Sudhakar Jan 30 '12 at 18:38
  • @Sudhakar: `RHS` = `Right Hand Side`. `/A` takes everything to the right of it and tries to use it as an arithmetic expression (eg., `1 + 1 * 3` – Ken White Jan 30 '12 at 18:41
  • Thank you Ken. Appreciate your time. – Sudhakar Jan 31 '12 at 20:10
  • It works ! But can you tell me why we have to add double % on batch file? – Kailash Dabhi Oct 28 '15 at 04:34
  • @KailashDabhi Because that's the way it works. :-) From the command line you use one `%`, from a batch file you double them. (It's most likely a need to escape them when being run by the batch process portion of cmd.exe.) – Ken White Oct 28 '15 at 12:40