【问题标题】:setting variable inside if else nested in for loop not working如果嵌套在for循环中,则在内部设置变量不起作用
【发布时间】:2013-10-23 12:52:52
【问题描述】:

我正在尝试在批处理文件中获取最高内存消耗的进程 ID。到目前为止,我已经达到了,但它不起作用。

@echo off
set old=0
for /f "TOKENS=1" %%a in ('wmic PROCESS where "Name='cmd.exe'" get WorkingSetSize ^| findstr [0-9]') do if %%a GTR %old% (set old=%%a)
echo %old%

【问题讨论】:

  • 您需要Setlocal ENABLEDELAYEDEXPANSION 并将%old% 替换为!old!。解释见set /?
  • 仅作记录,使用普通批处理最多只能比较 2 GB
  • 感谢 Butter,Foxdrive:最大 2GB,这意味着批处理变量不能保存超过 2*1024*1024*8 的数值。是吗?

标签: batch-file if-statement for-loop


【解决方案1】:

这应该可以...

@echo off 
Setlocal ENABLEDELAYEDEXPANSION
set old=0 
for /f "TOKENS=1" %%a in ('wmic PROCESS where "Name='cmd.exe'" get WorkingSetSize ^| findstr [0-9]') do (
  if %%a GTR !old! (
    set old=%%a
  ) 
 echo !old!
)

Set /? 解释延迟的环境变量扩展...

Delayed environment variable expansion is useful for getting around
the limitations of the current expansion which happens when a line
of text is read, not when it is executed.  The following example
demonstrates the problem with immediate variable expansion:

set VAR=before
if "%VAR%" == "before" (
        set VAR=after
        if "%VAR%" == "after" @echo If you see this, it worked
    )

would never display the message, since the %VAR% in BOTH IF statements
is substituted when the first IF statement is read, since it logically
includes the body of the IF, which is a compound statement.  So the
IF inside the compound statement is really comparing "before" with
"after" which will never be equal.  Similarly, the following example
will not work as expected:

    set LIST=
    for %i in (*) do set LIST=%LIST% %i
    echo %LIST%

in that it will NOT build up a list of files in the current directory,
but instead will just set the LIST variable to the last file found.
Again, this is because the %LIST% is expanded just once when the
FOR statement is read, and at that time the LIST variable is empty.
So the actual FOR loop we are executing is:

    for %i in (*) do set LIST= %i

which just keeps setting LIST to the last file found.

Delayed environment variable expansion allows you to use a different
character (the exclamation mark) to expand environment variables at
execution time.  If delayed variable expansion is enabled, the above
examples could be written as follows to work as intended:

    set VAR=before
    if "%VAR%" == "before" (
        set VAR=after
        if "!VAR!" == "after" @echo If you see this, it worked
    )

    set LIST=
    for %i in (*) do set LIST=!LIST! %i
    echo %LIST%

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多