0

Is it possible to output the result of a command to a variable when using pipes?

Example batch file script:

@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 Output:

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

Desired Output:

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

1 Answer 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

I'd try these changes, but I can guarantee nothing since whatever the sc is doing does nothing apparent on my machine.

The issue is that whereas the string is correctly applied, you need to escape the pipe character within the single-quotes contained between the parentheses in the Court Of King Caractacus.

I did try adding the caret to escape the pipe in the quoted argument to OutputCommandToVariable - but it intriguingly gained interest and appeared as a double-caret - possibly batch trying to escape the caret rather than the pipe...

Sign up to request clarification or add additional context in comments.

1 Comment

That's fantastic, thank you - I didn't realise you could do character replacements, nice trick. FYI: I also had to escape the quotes in the same way as the pipes. SC is Service Control - you can use it to start/stop/configure windows services. I use this instead of the NET command since it allows you to control remote machines as well as local. Thanks again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.