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

Windows批处理文件::使用管道时输出到变量,windows,command-line,batch-file,pipe,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

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

批处理文件脚本示例:

@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
我会尝试这些更改,但我不能保证什么,因为无论
sc
做什么,在我的机器上都看不到

问题是,尽管字符串应用正确,但在国王卡拉克塔克斯的宫廷中,需要在括号之间包含的单引号内转义管道字符


我确实尝试在引用的
OutputCommandToVariable
参数中添加插入符号以逃避管道,但它有趣地引起了人们的兴趣,并以双插入符号的形式出现-可能是批量尝试逃避插入符号而不是管道…

这太棒了,谢谢你-我不知道你可以进行字符替换,这是一个很好的技巧。仅供参考:我还必须以与管道相同的方式逃避引用。SC是服务控制-您可以使用它来启动/停止/配置windows服务。我使用这个命令而不是NET命令,因为它允许您控制远程机器和本地机器。再次感谢。
: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