windows - 循环批处理文件

标签 windows powershell batch-file

我正在编写一个在 Windows Server 2008 R2 上运行的批处理文件,它有一个 for 循环,无论我在网上阅读和尝试了多少教程,它都不会运行 for循环。

echo "Starting blur detection..."
if not exist %root%\output mkdir output
set tempnum = dir root | find /i "file"
set num = tempnum-5
for /l %idx in (0, 1, num) do (
   %root%\blurDetection.exe %root%\%img%__%idx%.tif %root%\output
   echo "blurDetection" %idx " of " %num )

Windows powershell 说“此时 idx 是意外的。” 有什么建议吗?

编辑:实际上我认为这一行导致了问题,我不认为它正在获取整数值作为返回。

set tempnum = dir root | find /i "file"

最佳答案

(在最初的帖子后添加)哦,我错过了最大的问题。这确实是这一行:

set tempnum = dir root | find /i "file"

你的意思是捕获dir的输出,对吧?这可以,AFAIK 只能在 for 中完成,除非你可以忍受输出到文件并稍后将其用作输入。

这种情况下的语法是:

FOR /F ["options"] %variable IN ('command') DO command [command-parameters]

注意这些不是反引号。

NT 脚本的最佳解释 for:http://www.robvanderwoude.com/ntfor.php

还有一点要注意:因为您似乎依赖文件名作为某个数字,所以我怀疑 dir/b 会是更好的选择。普通 dir 还将输出日期和文件大小等...


for 变量的 IIRC 名称不能超过一个字母。此外,在脚本文件中(与命令行相对),这些变量如下所示:

%%i

此外,

set num=tempnum-5

应该是

set /a num=%tempnum%-5

关于find 的另一个问题是您是否打算使用findstr。上下文太少,但 findstr 似乎更自然。

来自 for/?:

FOR %variable IN (set) DO command [command-parameters]

  %variable  Specifies a single letter replaceable parameter.
  (set)      Specifies a set of one or more files.  Wildcards may be used.
  command    Specifies the command to carry out for each file.
  command-parameters
             Specifies parameters or switches for the specified command.

To use the FOR command in a batch program, specify %%variable instead
of %variable.  Variable names are case sensitive, so %i is different
from %I.

特别注意这两个语句:

  • %variable 指定单个字母可替换参数。
  • 要在批处理程序中使用 FOR 命令,请指定 %%variable 而不是 %variable

for 循环的另一个特殊功能是您可以拆分输入,标记将按字母顺序分配给变量。所以在 for %a ... 中, token 将被分配给 %a%b 等等 ...set tempnum = dir根 |找到/i "文件"

关于windows - 循环批处理文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6779533/

相关文章:

function - PowerShell 模块函数不继承 WhatIf

windows - 在对 FFPROBE 的调用中相当于 linux wc -l 命令的 CMD?

batch-file - 批处理文件将文件夹中的文件夹列出到一个级别

windows - 使用批处理从文件中读取带有空格的行

c++ - C++ 中的 sleep 操作,平台 : windows

windows - 在 Windows : How to do it correctly? 上安装 CasperJS

r - 在 Windows 中使用 system() 将 git 命令发送到命令提示符时找不到 SSH key

windows - Windows 上的 Rsync : wrong permissions for created directories

unix - PowerShell 是否已准备好替换 Windows 上的 Cygwin shell?

excel - Powershell - Excel 将列的格式更改为文本