从批处理(.bat)调用PowerShell脚本获取返回值失败求助
解决批处理调用PowerShell脚本获取返回值的问题
问题根源分析
- 命令解析错误:你原
for /f调用中的powershell.exe -executionpolicy remotesigned ".\dang.ps1"会被PowerShell解析为执行字符串命令,而非运行脚本文件,因此它会尝试把".\dang.ps1"当作命令执行,触发CommandNotFoundException。 - 输出方式错误:PowerShell脚本顶层的
return不会将内容输出到标准输出(stdout),for /f无法捕获该值,需用Write-Output明确输出内容。
修正步骤
1. 调整PowerShell脚本
将脚本中的return替换为Write-Output,确保内容输出到控制台:
$crap="Pain in my butt" Write-Output $crap
2. 修正批处理的for /f命令
使用-File参数指定要运行的脚本文件,并调整参数顺序(执行策略参数需放在脚本路径前):
@echo off setlocal enabledelayedexpansion :: 捕获PowerShell脚本的输出 for /f "delims=" %%a in ('powershell.exe -ExecutionPolicy RemoteSigned -File ".\dang.ps1"') do ( set "$crap=%%a" ) :: 验证捕获结果 echo 捕获到的值: !$crap!
针对XML读取需求的扩展
如果要从XML中提取备份路径,可修改PowerShell脚本如下(假设XML文件为config.xml):
<!-- config.xml 示例内容 --> <backupConfig> <targetPath>D:\Backup\Files</targetPath> </backupConfig>
PowerShell脚本:
# 读取XML文件 $xmlContent = [xml](Get-Content ".\config.xml") # 提取目标路径 $backupPath = $xmlContent.backupConfig.targetPath # 输出路径供批处理捕获 Write-Output $backupPath
批处理中仍使用上述修正后的for /f逻辑,捕获到$backupPath后即可用于后续备份操作。
内容的提问来源于stack exchange,提问作者OldAndRetired
相关产品推荐
相关产品推荐

