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

Invoke-RestMethod返回PSObject添加成员后变为$null的问题

问题原因
  • Add-Member 默认不会返回修改后的对象,必须加上 -PassThru 参数才会输出修改后的对象。你当前的代码里,Add-Member 执行后没有输出任何内容,导致后续的 Export-Csv 接不到数据,最终出现对象变为 $null 或导出内容为空的情况。
  • 代码中的 $Result 变量未赋值,所以 Write-Host "$Result" 也无法输出有效内容。
修复方案

方案一:给 Add-Member 添加 -PassThru 参数

修改后的代码:

try { 
    $timestamp = Get-Date -Format "dd.MM.yyyy HH:mm"
    $Result = Invoke-RestMethod @Params 
    | Select-Object ip, country_code, as, is_proxy
    | Add-Member -MemberType NoteProperty -Name "query_date_and_time" -Value $timestamp -PassThru
    | Export-Csv $OutputPath -Append -NoTypeInformation

    Write-Host "$Result"
    
} catch { 
    Throw $_.Exception
}
  • -PassThru 参数会让 Add-Member 返回修改后的对象,确保管道能把数据传递给 Export-Csv。
  • 添加 -NoTypeInformation 可以避免CSV文件开头生成多余的类型注释行。

方案二:直接在 Select-Object 中添加计算属性(更简洁高效)

不需要使用 Add-Member,直接在选属性的步骤中新增时间戳列:

try { 
    $timestamp = Get-Date -Format "dd.MM.yyyy HH:mm"
    $Result = Invoke-RestMethod @Params 
    | Select-Object ip, country_code, as, is_proxy, @{Name='query_date_and_time'; Expression={$timestamp}}
    | Export-Csv $OutputPath -Append -NoTypeInformation

    Write-Host "$Result"
    
} catch { 
    Throw $_.Exception
}
  • 通过计算属性直接将时间戳整合到查询结果中,一步完成属性筛选和新增,从根源避免管道中丢失对象的问题。
额外注意事项
  • 如果是批量循环查询多个IP,要确保每次循环都重新执行 Get-Date 获取最新时间戳,保证每条记录的时间戳对应实际查询时间。
  • 首次导出时,-Append 参数会自动创建目标CSV文件,无需提前手动创建。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 00:02:10