如何在Power Automate Desktop中解析PowerShell脚本输出为多变量
解决Power Automate Desktop拆分PowerShell输出到独立变量的问题
核心原因
Power Automate Desktop(PAD)无法直接访问PowerShell脚本内部的变量,只能捕获脚本的标准输出内容。因此必须先让脚本以结构化格式输出数据,再在PAD中解析拆分。
方法1:用分隔符输出(简单高效)
步骤1:修改PowerShell脚本,用固定分隔符输出四个日期
将计算后的四个日期用逗号(或其他无冲突分隔符)拼接成一行输出,示例脚本:
# 计算当月首尾、上月首尾日期 $currentMonthStart = Get-Date -Day 1 -Hour 0 -Minute 0 -Second 0 | Get-Date -Format "yyyy-MM-dd" $currentMonthEnd = $currentMonthStart.AddMonths(1).AddDays(-1) | Get-Date -Format "yyyy-MM-dd" $lastMonthStart = $currentMonthStart.AddMonths(-1) | Get-Date -Format "yyyy-MM-dd" $lastMonthEnd = $currentMonthStart.AddDays(-1) | Get-Date -Format "yyyy-MM-dd" # 用逗号分隔输出所有值 "$currentMonthStart,$currentMonthEnd,$lastMonthStart,$lastMonthEnd"
步骤2:在PAD中拆分输出并赋值
- 添加「Split text」动作,设置:
- Text to split:
%PowerShellOutput% - Split by:
Comma (,) - 勾选Remove empty entries
- Text to split:
- 拆分后会得到一个数组变量(默认是
%SplitTextResult%),将数组元素分别赋值给目标变量:%NowDate%=%SplitTextResult[0]%(当月首日)%MonthEnd%=%SplitTextResult[1]%(当月末日)%LastMonthStart%=%SplitTextResult[2]%(上月首日)%LastMonthEnd%=%SplitTextResult[3]%(上月末日)
方法2:用JSON格式输出(更可靠,适合复杂数据)
如果日期格式包含特殊字符或后续需要扩展数据,推荐用JSON结构化输出:
步骤1:修改PowerShell脚本输出JSON
# 计算日期(统一格式) $currentMonthStart = Get-Date -Day 1 -Hour 0 -Minute 0 -Second 0 | Get-Date -Format "yyyy-MM-dd HH:mm:ss" $currentMonthEnd = $currentMonthStart.AddMonths(1).AddSeconds(-1) | Get-Date -Format "yyyy-MM-dd HH:mm:ss" $lastMonthStart = $currentMonthStart.AddMonths(-1) | Get-Date -Format "yyyy-MM-dd HH:mm:ss" $lastMonthEnd = $currentMonthStart.AddSeconds(-1) | Get-Date -Format "yyyy-MM-dd HH:mm:ss" # 构建对象并转为JSON输出 [PSCustomObject]@{ NowDate = $currentMonthStart MonthEnd = $currentMonthEnd LastMonthStart = $lastMonthStart LastMonthEnd = $lastMonthEnd } | ConvertTo-Json -Compress
步骤2:在PAD中解析JSON并赋值
- 添加「Parse JSON」动作,设置:
- JSON text:
%PowerShellOutput% - 点击Generate schema,粘贴脚本输出的JSON示例(比如
{"NowDate":"2024-05-01 00:00:00","MonthEnd":"2024-05-31 23:59:59","LastMonthStart":"2024-04-01 00:00:00","LastMonthEnd":"2024-04-30 23:59:59"})生成自动解析的结构
- JSON text:
- 解析后会得到一个对象变量(默认
%ParsedJSON%),直接将属性赋值给目标变量:%NowDate%=%ParsedJSON.NowDate%%MonthEnd%=%ParsedJSON.MonthEnd%- 以此类推
注意事项
- 确保PowerShell脚本中没有多余的输出(比如调试信息),否则会干扰拆分结果
- 选择分隔符时,要避免日期字符串中包含该字符(比如用竖线
|代替逗号,如果日期格式带逗号) - JSON方法支持更复杂的数据结构,后续扩展字段更方便
内容的提问来源于stack exchange,提问作者Vansh Shah
相关产品推荐
相关产品推荐

