3

Like the title says, I'm trying to take the output from a FIND command and save it to a variable. Specifically, I'm using:

DIR /b /s "C:\" | FIND "someexe.exe"

to locate a specific .exe file, which seems to work fine, but then I want to save the results of FIND to use later in the same script.

I've tried various different tweaks of:

for /f "usebackq" %%i in (`DIR /b /s "C:\" | FIND "someexe.exe"`) do SET foobar=%%i

but when I try to run the script the command window immediately closes (presumably due to some error, I tried putting a PAUSE command in the next line to no avail).

I assume it's some stupid minor thing that I'm doing wrong but if someone could show me what it is I'd appreciate it. Just for further reference, I don't care how many copies of "someexe.exe" exist, I just need the path for one of them.

mintchkin
  • 1,564
  • 2
  • 14
  • 13

1 Answers1

5

You should be getting this error: | was unexpected at this time.. Your immediate problem is unquoted special characters like | must be escaped using ^ when they appear in a FOR /F ('command').

for /f "usebackq" %%i in (`DIR /b /s "C:\" ^| FIND "someexe.exe"`) do SET foobar=%%i

It sounds like you are running your batch file by double clicking from either your desktop or Windows Explorer. That works, but then the window immediately closes after the batch terminates. In your case it terminates before reaching PAUSE because of the syntax error.

I always run my batch files from a command window: From the Start menu you want to run cmd.exe. That will open up a command console. Then CD to the directory where your batch file resides and then run the batch file by typing its name (no extension needed). Now the window stays open after the script terminates. You can examine your variables using SET, run another script, whatever.

There is no need to use FIND in your case - DIR can find the file directly. Also, the path of your file may include spaces, in which case it will be parsed into tokens. You need to set "DELIMS=" or "TOKENS=*" so that you get the complete path.

I never understand why people use USEBACKQ when they are executing a command. I only find it useful if I am trying to use FOR /F with a file and I need to enclose the file in quotes because of spaces and/or special characters.

Also, you may run across errors due to inaccessible directories. Redirecting stderr to nul cleans up the output. Here again, the > must be escaped.

for /f "delims=" %%F in ('dir /b /s "c:\someexe.exe" 2^>nul') do set foobar=%%F
dbenham
  • 127,446
  • 28
  • 251
  • 390