【发布时间】:2019-10-21 21:13:41
【问题描述】:
我有一个 Azure AD 应用程序,我需要在使用 Powershell 的服务主体内的 appRoles 部分中添加一个额外的 appRole。我使用 Invoke-RestMethod 到 Graph API 并使用以下 API Url:https://graph.microsoft.com/beta/servicePrincipals/AppID
Invoke-RestMethod 返回一个 PSCustomObject,然后我在 appRoles 部分添加另一个 PSCustomObject。然后,我将 PSCustomObject 转换为 JSON,并希望将 JSON 写回服务主体。问题是当我想将 JSON 写回服务主体时,我收到错误消息:
Invoke-RestMethod : 远程服务器返回错误:(400) Bad Request。
我也尝试使用图形资源管理器执行此操作,然后收到错误消息:
“从 JSON 读取器读取时发现意外的 'PrimitiveValue' 节点。应为 'StartArray' 节点。”
我认为 C# 中也存在同样的问题:Getting Bad Request error while updating email category with Office 365 API and HttpClient in C#
当我在 Graph Explorer 中执行 Get 时,每个 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 值和数组列表,以便将其添加到服务主体?
这是我正在使用的代码
$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'
【问题讨论】:
-
查看 convert-json 的
-depth参数。 docs.microsoft.com/en-us/powershell/module/… -
感谢莫瓦尔德!它适用于我收到的带有 ConvertTo-Json -Depth 4 的 Invoke-RestMethod 的 PsCustomObject。但是我怎样才能为我要添加的 PSCustomObject 创建一个字符串数组? $obj | Add-Member -MemberType NoteProperty -Name allowedMemberTypes -Value "User"
标签: powershell graph