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

PowerShell脚本构建API请求JSON体:remove字段无法添加内容排查

问题排查与修复方案

核心问题点

  • 循环作用域错误:$jsonBody定义在工作空间遍历循环内部,但JSON转换代码在循环外面,最终只会处理最后一次循环生成的$jsonBody。如果最后一个工作空间没有符合移除条件的项,remove字段就会为空;而且每次循环都会重新初始化$jsonBody,之前循环的修改会被直接覆盖。
  • 硬编码工作空间ID:获取安全设置的URL里写死了ABC!164,没有替换为当前遍历的工作空间ID$ws.id,导致每次都查询同一个固定工作空间的安全配置,而非目标工作空间的数据,可能根本没有需要移除的项。
  • (可选)数组操作冗余:用[ref]传递数组引用的方式没必要,PowerShell中直接通过返回新数组的方式构建remove列表更直观。

修改后的脚本示例

function Build-JsonBody {
    param (
        [string]$defaultSecurity,
        [array]$include,
        [array]$remove
    )

    $jsonBody = @{
        "default_security" = $defaultSecurity
        "include"          = $include
        "remove"           = $remove
    }

    return $jsonBody
}

# 简化移除项添加逻辑,直接返回新数组
function Add-ToRemoveSection {
    param (
        [array]$currentRemoveList,
        [string]$id,
        [string]$type
    )

    $itemToRemove = @{
        "id"   = $id
        "type" = $type
    }

    return $currentRemoveList + $itemToRemove
}

Write-Host "Finding all workspaces with Matter #$matter_num..."
$ws_search_url = $baseurl + "/work/api/v2/customers/$customer_id/libraries/ABC/workspaces?custom2=$matter_num"
$ws_resp = Invoke-RestMethod -Uri $ws_search_url -Headers $header -Method Get -ContentType "application/json"
$ws_results = $ws_resp.data.results

# 存储所有工作空间的更新请求体(按需使用)
$allUpdateBodies = @()

foreach($ws in $ws_results){
    $wsId = $ws.id
    # 替换为当前工作空间的ID,获取对应安全配置
    $sec_search_url = $baseurl + "/work/api/v2/customers/$customer_id/libraries/ABC/workspaces/$wsId/security"
    $sec_resp = Invoke-RestMethod -Uri $sec_search_url -Headers $header -Method Get -ContentType "application/json"
    $sec_results = $sec_resp.data.results

    $removeList = @()
    foreach ($item in $sec_results) {
        if ($item.id -ne "ADMIN_USERS") {
            $removeList = Add-ToRemoveSection -currentRemoveList $removeList -id $item.id -type $item.type
        }
    }

    # 构建当前工作空间的请求体
    $jsonBody = Build-JsonBody -defaultSecurity "private" -include @(@{ "id" = "ADMIN_USERS"; "access_level" = "full_access"; "type" = "group" }) -remove $removeList
    $allUpdateBodies += $jsonBody

    # 输出当前工作空间的JSON请求体
    $jsonBodyJson = $jsonBody | ConvertTo-Json -Depth 10
    Write-Host "=== Workspace $wsId Update Body ==="
    Write-Host $jsonBodyJson
}

# 后续可批量处理$allUpdateBodies中的请求体,比如逐个POST

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 16:56:21