切割弦后重复使用变量

时间:2015-02-18 11:52:07

标签: batch-file window

这是我在Windows批处理中的第一步,我提出了一个问题,

如果我将其添加到脚本文件中:

IF %p_monitorName%=="workflow_failed" (
    for /F "tokens=1 delims=," %%a in ("%p_monitorStatus: by =.%") do for /F "tokens=3 delims=:" %%b in ("%%a: by =.%") do for /F "tokens=1 delims= " %%c in ("%%b by =.%") do echo %%c >> %scriptdir%\..\logs\SIS2OVOOutput.txt
)

它有效,但如果我尝试在脚本中的任何其他地方使用%% c它失败了,你有任何建议吗?

1 个答案:

答案 0 :(得分:1)

%%c形式的变量仅在FOR循环上下文中有效。它们在FOR循环之外是未定义的或不可访问的。如果必须访问循环外的值,则将值传递给循环内的环境变量或CALL参数。

FOR变量在所有FOR循环中都是全局的。通常,您无法从循环内调用的子例程中访问FOR变量。但是你可以通过实例化一个新的FOR循环来获得访问权。

在循环内(在任何括号内的块中)使用常规%A%扩展无法访问在同一块中设置的新值。应该使用延迟扩展!A!。必须通过setlocal enableDelayedExpansion

启用延迟展开
@echo off
setlocal enableDelayedExpansion
set "A=Old Value"
for /f "delims=" %%A in ("Loop Value") do (
  echo Value within loop: %%A
  set "A=%%A"
  echo Value of %%A%% within loop: %A%
  echo Value of ^^!A^^! within loop: !A!
  call :sub "%%A"
)
for %%X in (dummy) do echo Value within X loop after A loop over: %%A
echo Value of %%A%% persists: %A%
exit /b

:sub
echo Value outside of loop: %%A
echo value of %%A%%: %A%
echo Value of %%A%% within subroutine: %A%
echo Value of ^^!A^^! within subroutine: !A!
echo value of %%~1: %~1
for %%X in (dummy) do echo Value within X loop while in subroutine: %%A
exit /b

- 输出 -

Value within loop: Loop Value
Value of Loop Value% within loop: Old Value
Value of !A! within loop: Loop Value
Value outside of loop: %A
value of %A%: Loop Value
Value of %A% within subroutine: Loop Value
Value of !A! within subroutine: Loop Value
value of %~1: Loop Value
Value within X loop while in subroutine: Loop Value
Value within X loop after A loop over: %A
Value of %A% persists: Loop Value