Windows批处理文件::使用管道时输出到变量

时间:2013-06-04 14:18:50

标签: windows command-line batch-file pipe

使用管道时是否可以将命令的结果输出到变量?

批处理文件脚本示例:

@echo off
cls
echo Script Started
setlocal enableextensions 

::prove that functionality works without pipes
call:OutputCommandToVariable "set computername" demo
echo.%demo%

::prove that the command itself works
call:IsServiceStartAutoDebug "MyComputerName" "wuauserv"

::now try it for real
call:IsServiceStartAuto "MyComputerName" "wuauserv"

::done
goto:end

:IsServiceStartAuto
call:OutputCommandToVariable "sc \\%~1 qc "%~2" | find "START_TYPE" | find "2"" IsServiceStartAuto
echo.%IsServiceStartAuto%
@goto:eof

:OutputCommandToVariable
set "%2="
for /f "delims=" %%a in ('%~1') do @set "%2=%%a"
::for /f "usebackq tokens=*" %%a in (`%~1`) do @set "%2=%%a"
@goto:eof

:IsServiceStartAutoDebug
sc \\%~1 qc "%~2" | find "START_TYPE" | find "2"
@goto:eof

:end
Echo Completed
::pause

脚本输出:

Script Started
COMPUTERNAME=MyComputerName
    START_TYPE         : 2   AUTO_START
| was unexpected at this time.

期望的输出:

Script Started
COMPUTERNAME=MyComputerName
    START_TYPE         : 2   AUTO_START
    START_TYPE         : 2   AUTO_START
Completed

1 个答案:

答案 0 :(得分:1)

:OutputCommandToVariable
SET val=%1
SET val=%val:|=^|%
set "%2="
for /f "delims=" %%a in (%val%) do set "%2=%%a"
::for /f "usebackq tokens=*" %%a in (`%~1`) do @set "%2=%%a"
goto:eof

我会尝试这些更改,但我无法保证,因为sc正在做的事情在我的机器上没有任何明显的效果。

问题是,在正确应用字符串的同时,您需要在Court of King Caractacus的括号中包含的单引号内转义管道字符。

我确实尝试在引用的OutputCommandToVariable参数中添加插入符号以逃避管道 - 但它有趣地引起了人们的兴趣并且作为双重插入符出现 - 可能是试图逃脱插入符号而不是管道的批处理。