从JSON读取器读取时,发现意外的'PrimitiveValue'节点。预计会出现“ StartArray”节点

时间:2019-06-06 10:50:49

标签: powershell graph

我有一个Azure AD应用程序,我需要在其中使用Powershell在服务主体的appRoles部分中添加一个额外的appRole。我将Invoke-RestMethod用于具有以下API网址的Graph API:https://graph.microsoft.com/beta/servicePrincipals/AppID

Invoke-RestMethod返回一个PSCustomObject,然后在appRoles部分中添加另一个PSCustomObject。然后,我将PSCustomObject转换为JSON,并想将JSON写回服务主体。问题是当我想将JSON写回到服务主体时,出现错误消息:

  

Invoke-RestMethod:远程服务器返回错误:(400)错误的请求。

我也尝试使用Graph资源管理器执行此操作,然后收到错误消息:

  

“从JSON读取器中读取时,发现意外的'PrimitiveValue'节点。应为'StartArray'节点。”

我认为C#中也存在相同的问题:Getting Bad Request error while updating email category with Office 365 API and HttpClient in C#

当我执行Get in Graph Explorer时,每个appRole都显示如下:

{
  "allowedMemberTypes": [
    "User"
  ],
  "description": "TEST-ALLOWALL",
  "displayName": "TEST-ALLOWALL",
  "id": "00000000-0000-0000-0000-00000000",
  "isEnabled": true,
  "origin": "ServicePrincipal",
  "value": "ARNROLEVALUE"
},

当我先执行Invoke-RestMethod然后执行ConvertTo-Json时,每个appRole都将显示如下:

{
  "allowedMemberTypes":  "User",
  "description":  "TEST-ALLOWALL",
  "displayName":  "TEST-ALLOWALL",
  "id":  "00000000-0000-0000-0000-00000000",
  "isEnabled":  true,
  "origin":  "ServicePrincipal",
  "value":  "ARNROLEVALUE"
},

如何确保Invoke-RestMethod保持allowedMemberTypes值类型为类似[“ User”]的数组/列表,而不是值“ User”?

又如何创建我自己的PSCustomObject allowedMembertypes值和arraylist,以便可以将其添加到服务主体中?

这是我正在使用的代码

$apiUrl = 'https://graph.microsoft.com/beta/servicePrincipals/000000-0000-0000-0000-00000000000'
$Data = Invoke-RestMethod -Headers $graphAPIReqHeader -Uri $apiUrl -Method Get

$obj = New-Object -TypeName PSObject
$obj | Add-Member -MemberType NoteProperty -Name allowedMemberTypes -Value "User"
$obj | Add-Member -MemberType NoteProperty -Name description -Value $RoleName
$obj | Add-Member -MemberType NoteProperty -Name displayName -value $RoleName
$obj | Add-Member -MemberType NoteProperty -Name id -value $Id
$obj | Add-Member -MemberType NoteProperty -Name isEnabled -value "true"
$obj | Add-Member -MemberType NoteProperty -Name origin -value "ServicePrincipal"
$obj | Add-Member -MemberType NoteProperty -Name value -value $Value

$Data.appRoles += $obj
$NewJson = $Data | ConvertTo-Json
$NewData = Invoke-RestMethod -Headers $graphAPIReqHeader -Uri $apiUrl -Body $NewJson -Method Patch -ContentType 'application/json' 

1 个答案:

答案 0 :(得分:0)

$input = @"
{
  "allowedMemberTypes": [
    "User"
  ],
   "description": "TEST-ALLOWALL",
   "displayName": "TEST-ALLOWALL",
  "id": "00000000-0000-0000-0000-00000000",
  "isEnabled": true,
  "origin": "ServicePrincipal",
  "value": "ARNROLEVALUE"
}
"@

$jObject = $input | convertfrom-json

$psObj = [Pscustomobject] @{
   AllowedMemberTypes = $jObject.allowedMemberTypes 
}
 $psObj.AllowedMemberTypes.Gettype()

$psObj.AllowedMemberTypes.Gettype()显示AllowedMemberTypes属于数组类型。

您可以找到代码online,并对其进行处理。

希望有帮助。