You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将PowerShell函数返回值作为批处理文件的变量使用

解决批处理调用PowerShell函数无返回值的问题

问题原因

你的PowerShell脚本仅定义了GetLatestText函数,但未执行该函数,导致运行脚本时没有任何输出,批处理的for /f命令无法捕获到内容,最终%var%为空。

解决方案

有两种可行的修改方式:

方式一:修改PowerShell脚本

在脚本末尾添加函数调用,确保执行脚本时直接输出结果:

function GetLatestText
{
    return "Hello World"
}
# 调用函数并输出返回值
GetLatestText

方式二:修改批处理命令

不改动原PowerShell脚本,在批处理的PowerShell命令中加载脚本后直接调用函数:

for /f "delims=" %%a in ('powershell -command "& '\\Rossi2\Shared\myPowershellScript.ps1'; GetLatestText"') do set "var=%%a"

echo %var%

说明

两种方式的核心都是确保PowerShell执行后输出Hello World,这样批处理的for /f才能捕获到该输出并赋值给变量var,最终正常打印出结果。

内容的提问来源于stack exchange,提问作者Rossi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 07:40:42