将命令输出保存到变量 [英] Save command output to variable
问题描述
在批处理文件中,我试图获取命令的输出并将其保存到变量中.
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 becausepath\to\my\folder
is in fact a UNC path (\\path\to\my\folder
), andcd \\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是意外的.
%%i was unexpected.
当我尝试直接在命令窗口中执行命令时.我试图转义<REP>
字符串(...find /c ""<REP>""') DO...
)周围的引号,也得到了相同的错误.
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?
推荐答案
您可以使用您最初提到的答案.您不必在那里cd
,但是您可以使用pushd
,它将为UNC路径分配一个临时驱动器号,当您执行popd
时,这些路径将被释放.
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
.
所以本质上:
pushd \\server\path
set count=0
for /d %%x in (*) do set /a count+=1
popd
这篇关于将命令输出保存到变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!