为什么此批处理脚本中的 FOR/f 循环评估空行? [英] Why is the FOR /f loop in this batch script evaluating a blank line?
问题描述
我正在尝试编写一个批处理脚本来获取(除其他外)计算机拥有的所有磁盘驱动器的列表.基本代码如下所示:
I'm trying to write a batch script that obtains (among other things) a list of all of the disk drives the computer has. The basic code looks something like this:
REM Build the list of disk drives to monitor
SETLOCAL enabledelayedexpansion
FOR /f "skip=1 tokens=1 delims=:" %%a in ('"WMIC logicaldisk WHERE drivetype=3 GET deviceid"') do (
SET "DISK_DATABASES=!DISK_DATABASES!%%a|"
SET "DRIVES_TO_MONITOR=!DRIVES_TO_MONITOR!%%a:\|"
)
我很明显地构建了两个格式略有不同的列表供以后使用.然而,当我运行它时,我得到的输出看起来像这样:
I pretty obviously build two lists with slightly different formats for use later. When I run this, however, the output I get looks something like this:
C|D|E||
C:\|D:\|E:\|:\|
现在,我希望在两种情况下都有尾随管道,我可以管理它,但我真的很困惑为什么那里有一个额外的空白条目.如果我手动运行 wmic
命令,我可以看到输出末尾确实有一个空行,但我的理解是 /f
专门应该忽略空行.
Now, I expect the trailing pipe in both cases and I can manage that, but I'm really confused why there is an extra blank entry in there. If I run the wmic
command manually, I can see that there is indeed a blank line at the end of the output, but my understanding is that /f
was specifically supposed to ignore blank lines.
如果我打开 ECHO
,看起来最后一行只是作为回车/换行符或类似的输入.有没有办法做我期待的事情?我错过了什么吗?我试图在循环中编写一个 if
条件来排除最后一行,但它......很时髦,从未奏效.我感谢任何/所有帮助.
If I turn ECHO
on, it looks like that last line is just coming in as a carriage return/newline or similar. Is there a way to do what I'm expecting? Am I missing something? I tried to write an if
condition in the loop to exclude this last line, but it was... funky and never worked. I appreciate any/all help.
推荐答案
在这种情况下,最后一次迭代产生的不是空项目,您只得到 C|D|E||
的输出使用 echo %DISK_DATABASES%
,
但是 echo !DISK_DATABASES!
会输出 ||D|E|
??
In this case the last iteration produces not an empty item, and you get your output of C|D|E||
only with echo %DISK_DATABASES%
,
but echo !DISK_DATABASES!
will output ||D|E|
??
那是因为最后一个元素是单个 <CR>
字符.
并且<CR>
字符在百分比扩展后被直接删除,但没有延迟扩展.
That's because the last element is a single <CR>
character.
And <CR>
characters are directly removed after the percent expansion, but not with delayed expansion.
你可以避免这种情况,使用百分比扩展来删除它们
You could avoid this, using the percent expansion to remove them
setlocal EnableDelayedExpansion
FOR /f "skip=1 tokens=1 delims=:" %%a in ('"WMIC logicaldisk WHERE drivetype=3 GET deviceid"') do (
set "item=%%a"
call :removeCR
if not "!item!"=="" (
SET "DISK_DATABASES=!DISK_DATABASES!!item!|"
SET "DRIVES_TO_MONITOR=!DRIVES_TO_MONITOR!!item!:\|"
)
)
goto :eof
:removeCR
:removeCR
set "Item=%Item%"
exit /b
这篇关于为什么此批处理脚本中的 FOR/f 循环评估空行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!