Reputation: 18743
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.
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.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?
Upvotes: 1
Views: 1904
Reputation: 354864
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
Upvotes: 4