James Ko
James Ko

Reputation: 34519

Batch files: How to capture output of a function in a variable?

Newbie to Batch scripting here. I'm trying to capture the output of a Batch 'function' (not exactly since Batch lacks built-in support for functions) to a variable. Here is my code:

@echo off
setlocal enabledelayedexpansion
goto main

:: Functions
:runps
powershell -NoProfile -ExecutionPolicy Bypass -Command "%1"
goto :eof

:appendToPath
set OLDPATHPS="[Environment]::GetEnvironmentVariable('PATH', 'User')"
for /f %%i in ('call :runps %OLDPATHPS%') do ^
    set OLDPATH=%%i
:: ...
goto :eof

:main
call :appendToPath

When I run this I get the following output from the console:

Invalid attempt to call batch label outside of batch script.

Why does this happen and what can I do to fix it?

Upvotes: 1

Views: 875

Answers (1)

Magoo
Magoo

Reputation: 80033

Call establishes a new cmd instance which cannot access a batch label in the old instance.

Solutions would include outputting the result to a file and reading the file or possibly

for /f %%i in ('%runps% "%OLDPATHPS%"') do (
    set OLDPATH=%%i
)

where runps has been set to powershell -NoProfile -ExecutionPolicy Bypass -Command

Upvotes: 2

Related Questions