首页 > 解决方案 > PowerShell 检索 MS Graph 3 级数据返回非 json 结果

问题描述

我得到了一个 PS 脚本来从 MS Graph 中检索 AuditLog 事件。脚本代码如下。它以 JSON 格式获取事件详细信息。

    # Create Authentication Token for MS Graph
Function GetAuthToken
{
    param
        (
        [Parameter(Mandatory=$true)]
        $TenantName
        )
    Import-Module Azure
    $clientId = "ef9bcdf0-a675-4cd5-9ec3-fa549f9ee4cf" 
    $redirectUri      = "https://RedirectURI.com" 
    $resourceAppIdURI = "https://graph.microsoft.com"
    $authority = "https://login.microsoftonline.com/$TenantName"
    $authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList $authority
    $Credential = Import-Clixml -Path "C:\MIMA\tom_admin_cred.xml"
    $AADCredential = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.UserCredential" -ArgumentList $credential.UserName,$credential.Password
    $authResult = $authContext.AcquireToken($resourceAppIdURI, $clientId,$AADCredential)
    return $authResult
}

Function Get-aAuditEvent
{
    param
        (
        [Parameter(Mandatory=$true)]
        $Tenant
        )

    if($Version -eq $null) {$Version='Beta'}
    #------Get the authorization token------#
    $token = GetAuthToken -TenantName $tenant 

    #------Building Rest Api header with authorization token------#
    $authHeader = @{
        'Content-Type'='application\json'
        'Authorization'=$token.CreateAuthorizationHeader()
        }

    $uri = "https://graph.microsoft.com/beta/auditlogs/directoryAudits/Directory_3WOOD_3967500"
    # $uri = "https://graph.microsoft.com/beta/auditlogs/directoryAudits"
    Try {
            $results = Invoke-RestMethod -Uri $uri –Headers $authHeader –Method Get 
            $results |ConvertTo-Json -depth 4
        }
    catch{
        Write-Host "Error while retrieving report!" -ForegroundColor red
        $auditReports = $_.Exception.Response
        }    
}


Get-aAuditEvent -Tenant "contoso.onmicrosoft.com"

代码的结果如下。注意“modifiedProperties”的内容不是 JSON 格式?这个属性的值似乎以某种方式转换为哈希表。但是,我尝试将此值放入哈希表中,但无论如何它都无法正确解析它。也许是因为“newValue”对于哈希表来说太长了?

    {
    "@odata.context":  "https://graph.microsoft.com/beta/$metadata#auditLogs/directoryAudits/$entity",
    "id":  "Directory_3WOOD_3967500",
    "category":  "Core Directory",
    "correlationId":  "559450b1-d1e8-4020-a420-4c3c6234ba44",
    "result":  "success",
    "resultReason":  "",
    "activityDisplayName":  "Update user",
    "activityDateTime":  "2018-10-13T14:57:33.328183Z",
    "loggedByService":  null,
    "initiatedBy":  {
                        "app":  null,
                        "user":  {
                                    "id":  "9327abf7-93ea-4007-a15c-9b77b5360cc9",
                                    "displayName":  null,
                                    "userPrincipalName":  "tom-admin@contoso.onmicrosoft.com",
                                    "ipAddress":  "\u003cnull\u003e"
                                }
                    },
    "targetResources":  [
                            {
                                "@odata.type":  "#microsoft.graph.targetResourceUser",
                                "id":  "2a58e6ca-2207-4fc0-ba5d-210cd5de25dc",
                                "displayName":  null,
                                "userPrincipalName":  "tom.chen@contoso.com",
                                "modifiedProperties":  [
                                                        "@{displayName=AssignedLicense; oldValue=[]; newValue=[\"[SkuName=ENTERPRISEPACK, AccountId=cdc4b90d-7fa9-4a12-8d58-c2872266673c, SkuId=6fd2c87f-b296-42f0-b197-1e91e994b900, DisabledPlans=[]]\"]}",
                                                        "@{displayName=AssignedPlan; oldValue=[]; newValue=[{\"SubscribedPlanId\":\"f0e58183-18c1-4fa6-939b-e78d050533b6\",\"ServiceInstance\":\"To-Do/NA001\",\"CapabilityStatus\":0,\"AssignedTimestamp\":\"2018-10-13T14:
57:33.1683839Z\",\"InitialState\":null,\"Capability\":null,\"ServicePlanId\":\"c87f142c-d1e9-4363-8630-aaea9c4d9ae5\"},{\"SubscribedPlanId\":\"ea0d7e34-84a0-4329-910a-f38d7d4f2c00\",\"ServiceInstance\":\"OfficeForms/NA001\",\"CapabilityStatus\":0,\"AssignedTimestamp\":\"
2018-10-13T14:57:33.1683839Z\",\"InitialState\":null,\"Capability\":null,\"ServicePlanId\":\"2789c901-c14e-48ab-a76a-be334d9d793a\"},{\"SubscribedPlanId\":\"0defa810-1846-4ebf-8c01-4b72f9dbec2c\",\"ServiceInstance\":\"MicrosoftStream/NA001\",\"CapabilityStatus\":0,\"Assi
gnedTimestamp\":\"2018-10-13T14:57:33.1683839Z\",\"InitialState\":null,\"Capability\":null,\"ServicePlanId\":\"9e700747-8b1d-45e5-ab8d-ef187ceec156\"},{\"SubscribedPlanId\":\"e56c4814-73b8-4a12-ac13-bd2236e1c61c\",\"ServiceInstance\":\"Deskless/NA001\",\"CapabilityStatus
\":0,\"AssignedTimestamp\":\"2018-10-13T14:57:33.1683839Z\",\"InitialState\":null,\"Capability\":null,\"ServicePlanId\":\"8c7d2df8-86f0-4902-b2ed-a0458298f3b3\"},{\"SubscribedPlanId\":\"ef68b42e-5730-41b8-b119-a78dd199cd39\",\"ServiceInstance\":\"ProcessSimple/NA001\",\"
CapabilityStatus\":0,\"AssignedTimestamp\":\"2018-10-13T14:57:33.1683839Z\",\"InitialState\":null,\"Capability\":null,\"ServicePlanId\":\"76846ad7-7776-4c40-a281-a386362dd1b9\"},{\"SubscribedPlanId\":\"d69c693a-dfc8-49f8-9bd2-68b570bc3dd8\",\"ServiceInstance\":\"PowerApp
sService/NA001\",\"CapabilityStatus\":0,\"AssignedTimestamp\":\"2018-10-13T14:57:33.1683839Z\",\"InitialState\":null,\"Capability\":null,\"ServicePlanId\":\"c68f8d98-5534-41c8-bf36-22fa496fa792\"},{\"SubscribedPlanId\":\"b3e7a5a5-bfae-4ae6-887c-ce9665de0610\",\"ServiceIn
stance\":\"TeamspaceAPI/NA001\",\"CapabilityStatus\":0,\"AssignedTimestamp\":\"2018-10-13T14:57:33.1683839Z\",\"InitialState\":null,\"Capability\":null,\"ServicePlanId\":\"57ff2da0-773e-42df-b2af-ffb7a2317929\"},{\"SubscribedPlanId\":\"c9dbc746-7d1d-449f-9a2c-f80c99df11f
2\",\"ServiceInstance\":\"ProjectWorkManagement/PROD_OC_Org_Ring_010\",\"CapabilityStatus\":0,\"AssignedTimestamp\":\"2018-10-13T14:57:33.1683839Z\",\"InitialState\":null,\"Capability\":null,\"ServicePlanId\":\"b737dad2-2f6c-4c65-90e3-ca563267e8b9\"},{\"SubscribedPlanId\
":\"6aa67dd9-afd1-47c4-b81f-065ba3495692\",\"ServiceInstance\":\"Sway/NA001\",\"CapabilityStatus\":0,\"AssignedTimestamp\":\"2018-10-13T14:57:33.1683839Z\",\"InitialState\":null,\"Capability\":null,\"ServicePlanId\":\"a23b959c-7ce8-4e57-9140-b90eb88a9e97\"},{\"Subscribed
PlanId\":\"6d4d99fc-d0e1-4350-a4da-cb79cadd739e\",\"ServiceInstance\":\"YammerEnterprise/NA009\",\"CapabilityStatus\":0,\"AssignedTimestamp\":\"2018-10-13T14:57:33.1683839Z\",\"InitialState\":null,\"Capability\":null,\"ServicePlanId\":\"7547a3fe-08ee-4ccb-b430-5077c50416
53\"},{\"SubscribedPlanId\":\"ac1fca1c-7d64-476c-b1f8-1c336ccac213\",\"ServiceInstance\":\"RMSOnline/AP\",\"CapabilityStatus\":0,\"AssignedTimestamp\":\"2018-10-13T14:57:33.1683839Z\",\"InitialState\":null,\"Capability\":null,\"ServicePlanId\":\"bea4c11e-220a-4e6d-8eb8-8
ea15d019f90\"},{\"SubscribedPlanId\":\"2cc87a99-6c05-4bf2-a8a7-4a75e26a6afd\",\"ServiceInstance\":\"MicrosoftOffice/NorthAmerica\",\"CapabilityStatus\":0,\"AssignedTimestamp\":\"2018-10-13T14:57:33.1683839Z\",\"InitialState\":null,\"Capability\":null,\"ServicePlanId\":\"
43de0ff5-c92c-492b-9116-175376d08c38\"},{\"SubscribedPlanId\":\"97006162-e810-4814-98e7-3ae3745b28bc\",\"ServiceInstance\":\"MicrosoftCommunicationsOnline/Instance04-S\",\"CapabilityStatus\":0,\"AssignedTimestamp\":\"2018-10-13T14:57:33.1683839Z\",\"InitialState\":null,\
"Capability\":null,\"ServicePlanId\":\"0feaeb32-d00e-4d66-bd5a-43b5b83db82c\"},{\"SubscribedPlanId\":\"10985cf4-2206-4e47-9910-426586912b1a\",\"ServiceInstance\":\"SharePoint/SPOS0017\",\"CapabilityStatus\":0,\"AssignedTimestamp\":\"2018-10-13T14:57:33.1683839Z\",\"Initi
alState\":null,\"Capability\":null,\"ServicePlanId\":\"e95bec33-7c88-4a70-8e19-b10bd9d0c014\"},{\"SubscribedPlanId\":\"e0592405-cc57-4152-8cc0-3f8e5651e47d\",\"ServiceInstance\":\"SharePoint/SPOS0017\",\"CapabilityStatus\":0,\"AssignedTimestamp\":\"2018-10-13T14:57:33.16
83839Z\",\"InitialState\":null,\"Capability\":null,\"ServicePlanId\":\"5dbe027f-2339-4123-9542-606e4d348a72\"},{\"SubscribedPlanId\":\"552916d8-55f1-44be-a7e1-9a56b8086a9b\",\"ServiceInstance\":\"exchange/apcprd03-001-01\",\"CapabilityStatus\":0,\"AssignedTimestamp\":\"2
018-10-13T14:57:33.1683839Z\",\"InitialState\":null,\"Capability\":null,\"ServicePlanId\":\"efb87545-963c-4e0d-99df-69c6916d9eb0\"}]}",
                                                        "@{displayName=Included Updated Properties; oldValue=; newValue=\"AssignedLicense, AssignedPlan\"}",
                                                        "@{displayName=TargetId.UserType; oldValue=; newValue=\"Member\"}"
                                                    ]
                            }
                        ],
    "additionalDetails":  [
                            {
                                "key":  "UserType",
                                "value":  "Member"
                            }
                        ]
}

这很奇怪,因为当我从 MS Graph Explorer 检索相同的事件时,我得到了不同的结果,这些结果都是正确的 JSON 格式。下面是 MS Graph Explorer 的输出。如您所见,“modifiedProperties”对仍然以 JSON 格式显示。

{
    "@odata.context": "https://graph.microsoft.com/beta/$metadata#auditLogs/directoryAudits/$entity",
    "id": "Directory_3WOOD_3967500",
    "category": "Core Directory",
    "correlationId": "559450b1-d1e8-4020-a420-4c3c6234ba44",
    "result": "success",
    "resultReason": "",
    "activityDisplayName": "Update user",
    "activityDateTime": "2018-10-13T14:57:33.328183Z",
    "loggedByService": null,
    "initiatedBy": {
        "app": null,
        "user": {
            "id": "9327abf7-93ea-4007-a15c-9b77b5360cc9",
            "displayName": null,
            "userPrincipalName": "tom-admin@contoso.onmicrosoft.com",
            "ipAddress": "<null>"
        }
    },
    "targetResources": [
        {
            "@odata.type": "#microsoft.graph.targetResourceUser",
            "id": "2a58e6ca-2207-4fc0-ba5d-210cd5de25dc",
            "displayName": null,
            "userPrincipalName": "tom.chen@contoso.com",
            "modifiedProperties": [
                {
                    "displayName": "AssignedLicense",
                    "oldValue": "[]",
                    "newValue": "[\"[SkuName=ENTERPRISEPACK, AccountId=cdc4b90d-7fa9-4a12-8d58-c2872266673c, SkuId=6fd2c87f-b296-42f0-b197-1e91e994b900, DisabledPlans=[]]\"]"
                },
                {
                    "displayName": "AssignedPlan",
                    "oldValue": "[]",
                    "newValue": "[{\"SubscribedPlanId\":\"f0e58183-18c1-4fa6-939b-e78d050533b6\",\"ServiceInstance\":\"To-Do/NA001\",\"CapabilityStatus\":0,\"AssignedTimestamp\":\"2018-10-13T14:57:33.1683839Z\",\"InitialState\":null,\"Capability\":null,\"ServicePlanId\":\"c87f142c-d1e9-4363-8630-aaea9c4d9ae5\"},{\"SubscribedPlanId\":\"ea0d7e34-84a0-4329-910a-f38d7d4f2c00\",\"ServiceInstance\":\"OfficeForms/NA001\",\"CapabilityStatus\":0,\"AssignedTimestamp\":\"2018-10-13T14:57:33.1683839Z\",\"InitialState\":null,\"Capability\":null,\"ServicePlanId\":\"2789c901-c14e-48ab-a76a-be334d9d793a\"},{\"SubscribedPlanId\":\"0defa810-1846-4ebf-8c01-4b72f9dbec2c\",\"ServiceInstance\":\"MicrosoftStream/NA001\",\"CapabilityStatus\":0,\"AssignedTimestamp\":\"2018-10-13T14:57:33.1683839Z\",\"InitialState\":null,\"Capability\":null,\"ServicePlanId\":\"9e700747-8b1d-45e5-ab8d-ef187ceec156\"},{\"SubscribedPlanId\":\"e56c4814-73b8-4a12-ac13-bd2236e1c61c\",\"ServiceInstance\":\"Deskless/NA001\",\"CapabilityStatus\":0,\"AssignedTimestamp\":\"2018-10-13T14:57:33.1683839Z\",\"InitialState\":null,\"Capability\":null,\"ServicePlanId\":\"8c7d2df8-86f0-4902-b2ed-a0458298f3b3\"},{\"SubscribedPlanId\":\"ef68b42e-5730-41b8-b119-a78dd199cd39\",\"ServiceInstance\":\"ProcessSimple/NA001\",\"CapabilityStatus\":0,\"AssignedTimestamp\":\"2018-10-13T14:57:33.1683839Z\",\"InitialState\":null,\"Capability\":null,\"ServicePlanId\":\"76846ad7-7776-4c40-a281-a386362dd1b9\"},{\"SubscribedPlanId\":\"d69c693a-dfc8-49f8-9bd2-68b570bc3dd8\",\"ServiceInstance\":\"PowerAppsService/NA001\",\"CapabilityStatus\":0,\"AssignedTimestamp\":\"2018-10-13T14:57:33.1683839Z\",\"InitialState\":null,\"Capability\":null,\"ServicePlanId\":\"c68f8d98-5534-41c8-bf36-22fa496fa792\"},{\"SubscribedPlanId\":\"b3e7a5a5-bfae-4ae6-887c-ce9665de0610\",\"ServiceInstance\":\"TeamspaceAPI/NA001\",\"CapabilityStatus\":0,\"AssignedTimestamp\":\"2018-10-13T14:57:33.1683839Z\",\"InitialState\":null,\"Capability\":null,\"ServicePlanId\":\"57ff2da0-773e-42df-b2af-ffb7a2317929\"},{\"SubscribedPlanId\":\"c9dbc746-7d1d-449f-9a2c-f80c99df11f2\",\"ServiceInstance\":\"ProjectWorkManagement/PROD_OC_Org_Ring_010\",\"CapabilityStatus\":0,\"AssignedTimestamp\":\"2018-10-13T14:57:33.1683839Z\",\"InitialState\":null,\"Capability\":null,\"ServicePlanId\":\"b737dad2-2f6c-4c65-90e3-ca563267e8b9\"},{\"SubscribedPlanId\":\"6aa67dd9-afd1-47c4-b81f-065ba3495692\",\"ServiceInstance\":\"Sway/NA001\",\"CapabilityStatus\":0,\"AssignedTimestamp\":\"2018-10-13T14:57:33.1683839Z\",\"InitialState\":null,\"Capability\":null,\"ServicePlanId\":\"a23b959c-7ce8-4e57-9140-b90eb88a9e97\"},{\"SubscribedPlanId\":\"6d4d99fc-d0e1-4350-a4da-cb79cadd739e\",\"ServiceInstance\":\"YammerEnterprise/NA009\",\"CapabilityStatus\":0,\"AssignedTimestamp\":\"2018-10-13T14:57:33.1683839Z\",\"InitialState\":null,\"Capability\":null,\"ServicePlanId\":\"7547a3fe-08ee-4ccb-b430-5077c5041653\"},{\"SubscribedPlanId\":\"ac1fca1c-7d64-476c-b1f8-1c336ccac213\",\"ServiceInstance\":\"RMSOnline/AP\",\"CapabilityStatus\":0,\"AssignedTimestamp\":\"2018-10-13T14:57:33.1683839Z\",\"InitialState\":null,\"Capability\":null,\"ServicePlanId\":\"bea4c11e-220a-4e6d-8eb8-8ea15d019f90\"},{\"SubscribedPlanId\":\"2cc87a99-6c05-4bf2-a8a7-4a75e26a6afd\",\"ServiceInstance\":\"MicrosoftOffice/NorthAmerica\",\"CapabilityStatus\":0,\"AssignedTimestamp\":\"2018-10-13T14:57:33.1683839Z\",\"InitialState\":null,\"Capability\":null,\"ServicePlanId\":\"43de0ff5-c92c-492b-9116-175376d08c38\"},{\"SubscribedPlanId\":\"97006162-e810-4814-98e7-3ae3745b28bc\",\"ServiceInstance\":\"MicrosoftCommunicationsOnline/Instance04-S\",\"CapabilityStatus\":0,\"AssignedTimestamp\":\"2018-10-13T14:57:33.1683839Z\",\"InitialState\":null,\"Capability\":null,\"ServicePlanId\":\"0feaeb32-d00e-4d66-bd5a-43b5b83db82c\"},{\"SubscribedPlanId\":\"10985cf4-2206-4e47-9910-426586912b1a\",\"ServiceInstance\":\"SharePoint/SPOS0017\",\"CapabilityStatus\":0,\"AssignedTimestamp\":\"2018-10-13T14:57:33.1683839Z\",\"InitialState\":null,\"Capability\":null,\"ServicePlanId\":\"e95bec33-7c88-4a70-8e19-b10bd9d0c014\"},{\"SubscribedPlanId\":\"e0592405-cc57-4152-8cc0-3f8e5651e47d\",\"ServiceInstance\":\"SharePoint/SPOS0017\",\"CapabilityStatus\":0,\"AssignedTimestamp\":\"2018-10-13T14:57:33.1683839Z\",\"InitialState\":null,\"Capability\":null,\"ServicePlanId\":\"5dbe027f-2339-4123-9542-606e4d348a72\"},{\"SubscribedPlanId\":\"552916d8-55f1-44be-a7e1-9a56b8086a9b\",\"ServiceInstance\":\"exchange/apcprd03-001-01\",\"CapabilityStatus\":0,\"AssignedTimestamp\":\"2018-10-13T14:57:33.1683839Z\",\"InitialState\":null,\"Capability\":null,\"ServicePlanId\":\"efb87545-963c-4e0d-99df-69c6916d9eb0\"}]"
                },
                {
                    "displayName": "Included Updated Properties",
                    "oldValue": null,
                    "newValue": "\"AssignedLicense, AssignedPlan\""
                },
                {
                    "displayName": "TargetId.UserType",
                    "oldValue": null,
                    "newValue": "\"Member\""
                }
            ]
        }
    ],
    "additionalDetails": [
        {
            "key": "UserType",
            "value": "Member"
        }
    ]
}

标签: jsonpowershelloffice365hashtablemicrosoft-graph-api

解决方案


我设法通过将“modifiedProperties”部分放入哈希表来解决问题(上次没有正确执行此操作)。我使用一个函数将 JSON 结果转换为 Hashtable。功能代码从这里复制。

Function ConvertTo-Hashtable {
    [CmdletBinding()]
    [OutputType('hashtable')]
    param (
        [Parameter(ValueFromPipeline)]
        $InputObject
    )

process {
    ## Return null if the input is null. This can happen when calling the function
    ## recursively and a property is null
    if ($null -eq $InputObject) {
        return $null
    }

    ## Check if the input is an array or collection. If so, we also need to convert
    ## those types into hash tables as well. This function will convert all child
    ## objects into hash tables (if applicable)
    if ($InputObject -is [System.Collections.IEnumerable] -and $InputObject -isnot [string]) {
        $collection = @(
            foreach ($object in $InputObject) {
                ConvertTo-Hashtable -InputObject $object
            }
        )

        ## Return the array but don't enumerate it because the object may be pretty complex
        Write-Output -NoEnumerate $collection
    } elseif ($InputObject -is [psobject]) { ## If the object has properties that need enumeration
        ## Convert it to its own hash table and return it
        $hash = @{}
        foreach ($property in $InputObject.PSObject.Properties) {
            $hash[$property.Name] = ConvertTo-Hashtable -InputObject $property.Value
        }
        $hash
    } else {
        ## If the object isn't an array, collection, or other object, it's already a hash table
        ## So just return it.
        $InputObject
    }
  }
}

$hashtable1 = @{}
$hashtable2 = @{}
$hashtable1 = Get-aAuditEvent -Tenant "contoso.onmicrosoft.com"|ConvertFrom-Json|ConvertTo-HashTable
$hashtable2 = $hashtable1.targetResources.modifiedProperties
$hashtable2[0].displayName
$hashtable2[0].oldValue
$hashtable2[0].newValue

代码的输出如下。我仍然需要锻炼如何正确解析“newValue”。但至少我可以展示已经完成了哪些操作以及更改了哪些操作。

AssignedLicense
[]
["[SkuName=ENTERPRISEPACK, AccountId=cdc4b90d-7fa9-4a12-8d58-c2872266673c, SkuId=6fd2c87f-b296-42f0-b197-1e91e994b900, DisabledPlans=[]]"]

推荐阅读