如何用PowerShell从Flowroute POST查询结果下载并提取CDR报告文件?
问题:PowerShell调用Flowroute API下载CDR报告遇到的问题
我正尝试用PowerShell通过REST API从Flowroute拉取CDR报告,刚接触API和PowerShell。目前已经成功发送POST请求生成CDR导出任务,但不知道怎么在脚本里自动获取下载链接、下载并解压.gz归档文件。试过用Get-Member从返回的NoteProperty里提取信息,但没成功。
我的POST请求代码
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]" $headers.Add("Content-Type", "application/vnd.api+json") $headers.Add("Authorization", "Basic <你的Base64编码凭证>") # 替换为实际授权字符串 $body = @" { `"data`": { `"type`": `"cdrexport`", `"attributes`": { `"filter_parameters`": { `"start_call_start_time`": `"2023-07-01 00:00:00"`, `"start_call_end_time`": `"2023-07-31 00:00:00"`, `"destination_numbers`": ["<目标电话号码>"] } } } } "@ # 替换为Flowroute实际API地址 $response = Invoke-RestMethod 'https://api.flowroute.com/v2/cdrexports' -Method 'POST' -Headers $headers -Body $body $response | ConvertTo-Json $response | Get-Member
Get-Member返回的响应结果
TypeName: System.Management.Automation.PSCustomObject Name MemberType Definition ---- ---------- ---------- Equals Method bool Equals(System.Object obj) GetHashCode Method int GetHashCode() GetType Method type GetType() ToString Method string ToString() data NoteProperty System.Management.Automation.PSCustomObject data=@{attributes=; id=586377; links=; type=cdrexport}
解决步骤与建议
1. 提取导出任务ID
不需要通过Get-Member,直接从响应对象中获取任务ID:
$exportId = $response.data.id Write-Host "CDR导出任务ID: $exportId"
2. 轮询任务状态,获取下载链接
Flowroute的CDR导出是异步任务,需定期查询状态直到任务完成:
$statusUrl = "https://api.flowroute.com/v2/cdrexports/$exportId" $downloadUrl = $null $maxAttempts = 30 # 最多轮询30次 $attemptCount = 0 while ($attemptCount -lt $maxAttempts) { $statusResponse = Invoke-RestMethod $statusUrl -Headers $headers $status = $statusResponse.data.attributes.status if ($status -eq "completed") { $downloadUrl = $statusResponse.data.attributes.download_url break } elseif ($status -eq "failed") { Write-Error "CDR导出任务失败" exit 1 } Write-Host "任务状态: $status,等待10秒后重试..." Start-Sleep -Seconds 10 $attemptCount++ } if (-not $downloadUrl) { Write-Error "超时未获取到下载链接" exit 1 }
3. 下载并解压.gz文件
下载文件
$outputPath = "C:\Temp\cdr_export.gz" Invoke-WebRequest -Uri $downloadUrl -OutFile $outputPath -Headers $headers
解压.gz文件
PowerShell原生Expand-Archive对单独.gz文件支持有限,可使用.NET类处理:
$outputFile = "C:\Temp\cdr_export.csv" # 假设解压后为CSV格式 $inputStream = New-Object System.IO.FileStream($outputPath, [System.IO.FileMode]::Open) $gzipStream = New-Object System.IO.Compression.GZipStream($inputStream, [System.IO.Compression.CompressionMode]::Decompress) $outputStream = New-Object System.IO.FileStream($outputFile, [System.IO.FileMode]::Create) $gzipStream.CopyTo($outputStream) $outputStream.Close() $gzipStream.Close() $inputStream.Close() Write-Host "CDR报告已解压至: $outputFile"
最佳实践
- 安全存储凭证:不要在脚本中明文写授权信息,使用
Get-Credential转换为Base64,或用PowerShell SecretManagement模块存储。 - 添加错误处理:给
Invoke-RestMethod添加try/catch块,处理网络错误、API返回的异常信息。 - 设置合理超时:轮询时限制最大尝试次数,避免无限循环。
- 日志记录:记录任务ID、状态变化、下载路径等信息,方便排查问题。
内容的提问来源于stack exchange,提问作者crizpyy
相关产品推荐
相关产品推荐

