0

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

示例批处理文件脚本:

@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
4

1 回答 1

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- 但它有趣地引起了兴趣并显示为双插入符号 - 可能是批次试图逃避插入符号而不是管道......

于 2013-06-04T15:01:24.967 回答