Save output from FIND command to variable

后端 未结 1 2050
鱼传尺愫
鱼传尺愫 2021-01-06 13:36

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 \"some         


        
相关标签:
1条回答
  • 2021-01-06 13:56

    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
    
    0 讨论(0)
提交回复
热议问题