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?

Community
  • 1
  • 1
Otiel
  • 18,404
  • 16
  • 78
  • 126
  • 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. – Andriy M Nov 17 '11 at 17:50
  • 1
    Possible duplicate of [Capture output command CMD](http://stackoverflow.com/questions/14646575/capture-output-command-cmd) – aschipfl Nov 24 '16 at 16:24

1 Answers1

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
Joey
  • 344,408
  • 85
  • 689
  • 683