1

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?

Community
  • 1
  • 1
James Ko
  • 32,215
  • 30
  • 128
  • 239

1 Answers1

2

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

Magoo
  • 77,302
  • 8
  • 62
  • 84