【问题标题】:Use DelayedExpansion in nested FOR loops在嵌套 FOR 循环中使用 DelayedExpansion
【发布时间】:2018-03-13 21:31:09
【问题描述】:

我的目标是列出 PC 上的本地硬盘并在每个硬盘上搜索特定文件。如果找到,将文件的路径输出到名为“PCNAME.txt”的文本文件。我的期望如下:

set filename="abc.exe"
set uncpath="%userprofile%\desktop\"
set fullpath=%uncpath%\%computername%.txt

for /f %%a in ('wmic logicaldisk where "description='Local Fixed Disk'" get Caption ^| find ":"') do (
set letter=%%a
cd %letter%\ 

for /R %%f in (%filename%) do @IF EXIST %%f @echo File Location^(s^) Identified: >> %fullpath% & goto :search

:search
for /R %%f in (%filename%) do @IF EXIST %%f set filenew=%%f & call :trim
echo. >> %fullpath%
exit /b

:trim
set filenew=%filenew:"=%
@echo %filenew% >> %fullpath%
)

当删除第一个 FOR 循环并将当前工作目录更改为 C:\ 驱动器时,上述脚本可以正常工作。但我希望它在所有本地硬盘驱动器上运行。经过大量的谷歌搜索,我想这种方法可能是使用 DelayedExpansion。我也明白 FOR 循环内的 goto 正在取消循环。但我无法完全修复脚本。

我还想知道是否可以完全消除“修剪”标签,而是使用 DelayedExpansion 或其他方法直接在“搜索”标签下删除双引号。任何帮助将不胜感激。

【问题讨论】:

  • Dir /b /s C:\filename.exe 搜索硬盘。 Dir /b /s C:\filename.exe > "%userprofile%\desktop\%computername%.txt"。您只需要循环来获取驱动器号。

标签: windows batch-file for-loop nested-loops


【解决方案1】:

永远不要在批处理脚本中使用多行代码块。

@for ... do @call :SubroutineName %%G
@exit /b 0
:Subroutine
rem Whatever.

然后在子例程中完成您的工作,而不必担心多行代码块中涉及的所有问题。您会发现使用 echo on 也更容易调试此类代码。

【讨论】:

    【解决方案2】:

    这是使用WMICDir 的一种方法:

    @Echo Off
    Set "filename=abc.exe"
    Set "uncpath=%userprofile%\desktop"
    Set "fullpath=%uncpath%\%computername%.txt"
    
    Echo File Location(s) Identified:>"%fullpath%"
    Set "_="
    (For /F "Skip=1" %%A In (
        'WMIC LogicalDisk Where "DriveType='3'" Get DeviceID 2^>Nul') Do (
        For /F "Delims=" %%B In ('Dir /B/S/A-D-L "%%A\%filename%" 2^>Nul'
        ) Do Set "_=T" & Echo %%B))>>"%fullpath%"
    If Not Defined _ Del "%fullpath%"
    

    如果您只想要没有文件名本身的位置,请将11 行上的%%B 更改为%%~dpB

    【讨论】:

    • 这可以完成工作,但生成的文本文件中有重复的位置条目。
    • 我感觉Where 命令可能是问题所在。 (默认情况下,它还会在 PATH 环境变量指定的路径中搜索,因此可能会在每次驱动器号搜索期间重复在 %Path% 中找到的任何内容)。我已将其替换为 Dir 命令,再次尝试我编辑的答案,看看是否有帮助。
    猜你喜欢
    • 2021-12-11
    • 2015-01-28
    • 2021-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多