Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/batch-file/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
If statement 将带有变量存在性测试的Windows批处理脚本块传递给另一个命令_If Statement_Batch File_Pipe_Multiline_Scriptblock - Fatal编程技术网

If statement 将带有变量存在性测试的Windows批处理脚本块传递给另一个命令

If statement 将带有变量存在性测试的Windows批处理脚本块传递给另一个命令,if-statement,batch-file,pipe,multiline,scriptblock,If Statement,Batch File,Pipe,Multiline,Scriptblock,我试图让下面的代码工作,测试管道中是否存在变量,这是我想要执行的真实代码的简化,其中包含脚本块中的其他代码,但这说明了问题: ( if defined some_variable echo ok ) | more echo was unexpected at this time 它给我的信息是“echo此时出乎意料”。在“if”语句之后引用带括号的语句并不能解决问题,它只是抱怨括号 ( if defined some_variable ( echo ok ) ) | more ( was un

我试图让下面的代码工作,测试管道中是否存在变量,这是我想要执行的真实代码的简化,其中包含脚本块中的其他代码,但这说明了问题:

( if defined some_variable echo ok ) | more
echo was unexpected at this time
它给我的信息是“echo此时出乎意料”。在“if”语句之后引用带括号的语句并不能解决问题,它只是抱怨括号

( if defined some_variable ( echo ok ) ) | more
( was unexpected at this time.
“if”语句的两种变体在不在被管道传输的代码块中时都可以工作

if defined some_variable echo ok
ok
if defined some_variable ( echo ok )
ok
此外,我可以执行代码块,但输出到一个文件,该文件用于捕获脚本块的输出,特别是即使脚本块中有多行代码:

( if ok defined some_variable echo ok ) > some_text_file.txt
这种样式的“如果”在脚本块到管道结构中工作:

( if 1==1 echo ok ) | more
ok
( if NOT 1==2 echo ok ) | more
ok
但我不明白为什么带有“defined”关键字的生存测试会完全轰炸这个管道结构

我的最终目标是让下面的代码在批处理脚本中工作(它所做的工作比下面的示例要多),但问题归结为在开始时提到的简化。下面的代码将作为一个批处理脚本,将输出回送到命令提示符和日志文件,但脚本块中的变量检查会破坏它

( 
  echo some_stuff_like_a_program_header
  
  #test existence of a variable and if not defined earlier in script then echo some stuff
  if NOT defined some_variable then_alert_user_with_error_msg
  
  if some_variable==some_value (do_some_stuff) else (do_other_stuff)
  
) | powershell.exe -command '& { $input | tee-object -file out.log }'

这是解析器的一个错误,if语句将被压缩为
if definedsome_变量echo ok

您可以看到,在
定义的
某些变量

您可以使用后期变量展开来解决此问题

set "myLine=if defined path echo ok"
echo pipe | ( %%myLine%%)
或使用转义空格(来自@previousing)

要查看内部发生的情况,可以尝试此调试构造

@echo off
setlocal
(set \n=^
%=empty=%
)
set "debug=echo ### %%cmdcmdline%% ^) %%\n%%"
echo dummy | (
    %debug%
    if defined some_variable echo ok
)
@echo off
setlocal
(set \n=^
%=empty=%
)
set "debug=echo ### %%cmdcmdline%% ^) %%\n%%"
echo dummy | (
    %debug%
    if defined some_variable echo ok
)