使用管道时是否可以将命令的结果输出到变量?
示例批处理文件脚本:
@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