PowerShell如何从测试报告文本中提取指定行末尾数值存入变量?
PowerShell测试报告数值提取修改方案
完整修改后脚本
# 取最新的目标测试报告文件 $file = Get-ChildItem -Path $reportDir -Include "$reportName.$fileformat" -Recurse | Sort-Object LastAccessTime | Select-Object -Last 1 # 提取Number of test steps末尾数值 $testStepCount = (Get-Content $file.FullName | Select-String -Pattern "Number of test steps").Line -replace '.*\s+(\d+)\s*$','$1' # 提取Failed TestStep Count末尾数值 $failStepCount = (Get-Content $file.FullName | Select-String -Pattern "Failed TestStep Count").Line -replace '.*\s+(\d+)\s*$','$1' # 输出自定义JSON,使用here-string格式无需手动转义双引号 Write-Host @" { "operation": "$environment", "status": "OK", "ProjectName": "$project", "TestSuit": "$testSuite", "TestCase": "$testCase", "TestStep": "$testStepCount", "FailStep": "$failStepCount", "Coverage": "$value" } "@
核心修改说明
- 优化文件获取逻辑:
Get-ChildItem匹配到多个文件时会返回数组,追加Select-Object -Last 1取最新访问时间的单份报告,避免后续读取文件报错 - 数值提取逻辑:用
-replace配合正则捕获行末尾的数字:- 正则
.*\s+(\d+)\s*$的含义是:匹配任意字符直到最后一段空白符,捕获后面连续的数字作为分组1,忽略行尾多余空白 - 替换为
$1直接取捕获到的数字,即可得到目标数值
- 正则
- 如需避免变量包含特殊字符导致JSON格式错误,可以改用PowerShell内置对象转JSON的方案,兼容性更强:
$outputObj = [PSCustomObject]@{ operation = $environment status = "OK" ProjectName = $project TestSuit = $testSuite TestCase = $testCase TestStep = $testStepCount FailStep = $failStepCount Coverage = $value } Write-Host ($outputObj | ConvertTo-Json -Depth 10)
内容的提问来源于stack exchange,提问作者IraIra25
相关产品推荐
相关产品推荐

