【问题标题】:Batch files: How to capture output of a function in a variable?批处理文件:如何在变量中捕获函数的输出?
【发布时间】:2015-12-13 19:11:08
【问题描述】:

这里是批处理脚本的新手。我正在尝试将Batch 'function' 的输出(不完全是因为 Batch 缺乏对函数的内置支持)到变量中。这是我的代码:

@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

当我运行它时,我会从控制台得到以下输出:

Invalid attempt to call batch label outside of batch script.

为什么会发生这种情况,我可以做些什么来解决它?

【问题讨论】:

    标签: windows batch-file command-line cmd


    【解决方案1】:

    Call 建立一个新的cmd 实例,该实例无法访问旧实例中的批次标签。

    解决方案包括将结果输出到文件并读取文件或可能

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

    其中runps 已设置为powershell -NoProfile -ExecutionPolicy Bypass -Command

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-07
      相关资源
      最近更新 更多