带变量的嵌套FOR [英] Nested FOR with variables

查看:125
本文介绍了带变量的嵌套FOR的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个批处理脚本,该脚本将遍历计算机列表,从计算机中读取文件,对文件名进行delim,然后回显计算机名和文件名结果.我遇到的问题是要在嵌套的FOR/R命令中填充计算机名称变量.这是我的脚本:

I'm attempting to write a batch script that will go through a list of computers, read a file from the computer, delim the file name, then echo the computer name and the file name result. The issue I'm having is getting the computer name variable to populate in the nested FOR /R command. Here is my script:

@ECHO OFF
SetLocal EnableDelayedExpansion
SET LIST=Computers.txt
FOR /F %%A IN (%LIST%) DO (
    FOR /R \\%%A\c$\folder1\folder2 %%B IN (*.txt) DO (
        FOR /F "tokens=2 delims=." %%C IN ("%%B") DO (ECHO %%A %%C
        )
    )
)
EndLocal

文件名类似于RB-C1SRC20160716CL.P17.txt.所以我要寻找的结果是

The filename is something like RB-C1SRC20160716CL.P17.txt. So the result I am looking for is

MyPCName P17

但是我得到一个空白的结果.我发现是从文本文件填充%% A var,但未填充FOR/R中的%% A var.如果回显FOR命令,则会看到FOR/R \%a \ folder1 \ folder2而不是FOR/R \ MyPCName \ folder1 \ folder2.这种故障使脚本的其余部分无法正常工作.

But I get a blank result. What I have found is that %%A var is being populated from the text file but the %%A var in the FOR /R is not populating. If I ECHO ON the FOR commands I'm seeing FOR /R \%a\folder1\folder2 instead of FOR /R \MyPCName\folder1\folder2. This breakdown is keeping the rest of the script from working properly.

推荐答案

for /R命令的根目录不能由另一个for变量(如%%I)或使用延迟扩展(),很不幸.您需要通过正常扩展的变量(%VAR%)或通过参数引用(%1%2,...)来迭代地指定它.

The root directory of a for /R command cannot be given by another for variable (like %%I) nor a variable using delayed expansion (!VAR!), unfortunately. You need to specify it either iterally, by a normally expanded variable (%VAR%) or by an argument reference (%1, %2,...).

一个好的解决方法是将for /R循环放在子例程中,并使用call从主例程中调用它.根路径(包含该变量的根路径)需要作为参数传递给call.在子例程中,它是由参数引用(如%1)引用的.

A good work-around is to place the for /R loop in a sub-routine and use call to call it from your main routine. The (variable holding the) root path needs to be passed as an argument to call. In the sub-routine it is referred to by an argument reference (like %1).

看看帖子"

Take a look at this answer of the post "Get size of the sub folders only using batch command" to see how this can be accomplished.

这篇关于带变量的嵌套FOR的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆