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

使用Invoke-RestMethod与foreach循环调用API时遇用户ID查找失败问题

PowerShell调用API循环报错问题解决

问题描述

编写调用API的PowerShell脚本时,使用Invoke-RestMethod结合循环出现报错,提示{"Message":"User with specified id was not found."}。脚本里$apikey和$allusers的输出看起来正常,单独调用单个用户ID的API也能正常运行,但循环执行时就出错。原始代码如下:

$url = "/api/Rest/v1"

$Body = @{
    Username = ""
    Password = ""
    Privatekey = ""
}

$apikey = Invoke-RestMethod -Method 'Post' -Uri $url/Authenticate -Body $body 

$headers = @{
    'Authorization' = $apikey

}

$allusers = Invoke-RestMethod -Uri $url/Users -Method Get -Headers $headers | ft -HideTableHeaders Id

foreach ($userid in $allusers)
{
echo $userid
Invoke-RestMethod -Uri $url/Users/$userid -Method Get -Headers $headers 
echo "test"
}

问题原因

你推测的没错,问题就出在ft(即Format-Table)命令上。Format-Table是用来格式化输出供人阅读的工具,它返回的不是原始的用户ID字符串,而是包含格式化渲染信息的对象。虽然控制台显示的ID看起来正常,但实际循环时传递给API的并不是纯ID字符串,导致API无法识别对应的用户。

解决方案

直接从Invoke-RestMethod返回的对象中提取ID属性,用Select-Object -ExpandProperty Id替代Format-Table,这样得到的是纯字符串数组,循环时就能正确传递ID值给API。

修改后的关键代码

# 替换原来的$allusers赋值行
$allusers = Invoke-RestMethod -Uri $url/Users -Method Get -Headers $headers | Select-Object -ExpandProperty Id

完整修改后的脚本

$url = "/api/Rest/v1"

$Body = @{
    Username = ""
    Password = ""
    Privatekey = ""
}

$apikey = Invoke-RestMethod -Method 'Post' -Uri $url/Authenticate -Body $body 

$headers = @{
    'Authorization' = $apikey

}

# 改用Select-Object提取纯ID字符串数组
$allusers = Invoke-RestMethod -Uri $url/Users -Method Get -Headers $headers | Select-Object -ExpandProperty Id

foreach ($userid in $allusers)
{
    Write-Host $userid
    Invoke-RestMethod -Uri "$url/Users/$userid" -Method Get -Headers $headers 
    Write-Host "test"
}

补充说明

  • Select-Object -ExpandProperty Id会直接取出每个用户对象的Id属性值,生成纯字符串数组,完全匹配API调用的参数要求。
  • 建议用Write-Host代替echo,更符合PowerShell的使用规范,输出控制也更灵活。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 20:55:19