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

PowerShell调用Snipe IT API查询资产存在性的Invoke-RestMethod问题

解决Snipe IT API查询资产存在性的返回结构问题

首先明确:Snipe IT的资产查询接口在无匹配资产时,不会返回status:"error"的错误结构,而是返回正常的列表响应,只是rows数组为空。你看到的@{total=1; rows=System.Object[]}是合法的查询结果,说明API请求成功,但没有找到对应资产。

正确的判断逻辑

不要尝试访问$assetCheckResponse.status,而是通过检查rows数组的长度来判断资产是否存在:

function Check-AssetExists {
    param(
        [string]$SerialNumber,
        [string]$ApiUri,
        [hashtable]$Headers
    )

    $queryUri = "$ApiUri/hardware?serial=$SerialNumber"
    $response = Invoke-RestMethod -Uri $queryUri -Method Get -Headers $Headers

    # 判断资产是否存在
    return $response.rows.Count -gt 0
}

# 调用示例
$assetExists = Check-AssetExists -SerialNumber "XXX123" -ApiUri "https://your-snipeit-instance/api/v1" -Headers @{"Authorization" = "Bearer YOUR_API_KEY"}
if ($assetExists) {
    Write-Host "资产存在"
} else {
    Write-Host "资产不存在"
}

确认API真实返回结构

如果不确定API的返回格式,先用Invoke-WebRequest获取原始JSON响应,避免PowerShell自动解析后隐藏细节:

$queryUri = "https://your-snipeit-instance/api/v1/hardware?serial=不存在的序列号"
$rawResponse = Invoke-WebRequest -Uri $queryUri -Method Get -Headers $Headers
# 输出原始JSON
Write-Host $rawResponse.Content

无匹配资产时,你会看到类似这样的合法响应:

{
  "total": 0,
  "rows": []
}

处理真正的API错误

只有当请求本身出错(比如无效API密钥、权限不足、参数格式错误)时,API才会返回status:"error"的结构。此时Invoke-RestMethod会抛出异常,需要用try/catch捕获并解析错误信息:

try {
    $response = Invoke-RestMethod -Uri $queryUri -Method Get -Headers $Headers
    return $response.rows.Count -gt 0
} catch {
    # 读取错误响应内容
    $errorStream = $_.Exception.Response.GetResponseStream()
    $streamReader = New-Object System.IO.StreamReader($errorStream)
    $errorContent = $streamReader.ReadToEnd() | ConvertFrom-Json
    
    Write-Host "API请求失败: $($errorContent.status) - $($errorContent.messages)"
    return $false
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 15:12:13