1

In a batch file, I am trying to fetch the output of a command and save it to a variable.

The goal of my command is to count the number of folders in a certain folder.

  • I can't use the trick provided in this accepted answer because I would have to do cd path\to\my\folder to get to the current directory. Unfortunately, I can't do this command because path\to\my\folder is in fact a UNC path (\\path\to\my\folder), and cd \\some\UNC\path is not supported by the windows cmd.
  • I am aware of this answer but I don't want to use a temporary file.

So I tried to do the following:

  • To obtain the number of folders, I use:

    dir \\path\to\my\folder | find /c "<REP>"
    

    This works fine and returning me a number as I would expect.

  • To retrieve the output of this command in a batch variable, I tried:

    FOR /F "TOKENS=*" %%i IN ('\\path\to\my\folder | find /c "<REP>"') DO 
    SET value = %%i
    

    But without success, the error message being...

    | was unexpected.

    ...when I execute the batch file and...

    %%i was unexpected.

    when I try to execute the command directly in a command window. I tried to escape the quotes around the <REP> string (...find /c ""<REP>""') DO...), got me the same error.

Am I on the right path to retrieve the output in a variable? What should I do to resolve the error message?
Or maybe there is a simpler way to set a command output in a variable?

2
  • 2
    Addressing the issues you've encountered: 1) | should be escaped in that context like this: ^|, and 2) %%i is only used in batch files, and %i is its counterpart for using directly at the command prompt. Commented Nov 17, 2011 at 17:50
  • 1
    Possible duplicate of Capture output command CMD Commented Nov 24, 2016 at 16:24

1 Answer 1

4

You can use the answer you first mentioned. You don't have to cd there, but you can use pushd which will allocate a temporary drive letter for UNC paths which will be released when you do a popd.

So in essence:

pushd \\server\path
set count=0
for /d %%x in (*) do set /a count+=1
popd
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.