Powershell - Sorting JSON data by date

Viewed 56

I've been looking at the Microsoft Graph API and have been trying to sort through user devices based on the Last Signin Date.

I've been able to query the api for a user and convertfrom-json into custom objects that I can iterate through. The problem I'm having, is pulling the most recent device from the list.

This is what I have, and forgive me, I'm no expert so this is likely over simplistic.. I'm trying to use sort-object, but it doesn't appear to do anything in this code.. Any advice or direction would be amazing!

### Authenticate ###
# Application (client) ID, tenant ID and secret
$clientId = "_REDACTED_"
$tenantId = "_REDACTED_"
$clientSecret = '_REDACTED_'
$webData = $null
$jsonWebData = $null

# Construct URI
$uri = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token"

# Construct Body
$body = @{
    client_id     = $clientId
    scope         = "https://graph.microsoft.com/.default"
    client_secret = $clientSecret
    grant_type    = "client_credentials"
}

# Get OAuth 2.0 Token
$tokenRequest = Invoke-WebRequest -Method Post -Uri $uri -ContentType "application/x-www-form-urlencoded" -Body $body -UseBasicParsing

# Access Token
$token = ($tokenRequest.Content | ConvertFrom-Json).access_token


### Query ###
$Headers = @{"Authorization" = "Bearer $token" }
$currentUri = "https://graph.microsoft.com/beta/users/_REDACTED_/ownedDevices"


    # API Call
    Write-Host "`r`nQuerying $currentUri..." -ForegroundColor Yellow
    $jsonWebData = Invoke-WebRequest -Method "GET" -Uri $currentUri -ContentType "application/json" -Headers $Headers -ErrorAction Stop

    #Sort Data
    $webData = $jsonWebData.content | ConvertFrom-Json | Sort-Object -Property ($_.value.approximateLastSignInDateTime)
    $webdata.value.approximateLastSignInDateTime

Thanks,

1 Answers

MS Graph calls support sorting the output on the server side by specifying sortProperties, though not all object properties support it:

"sortProperties": [
          {
              "name": "approximateLastSignInDateTime",
              "isDescending": false
          }
      ]

https://docs.microsoft.com/en-us/graph/search-concept-sort


Another option is using the powershell sdk/wrapper module: Microsoft.Graph.Users, since it automatically converts most data types into their powershell equivalent. Example cmdlet: Get-MgUserOwnedDevice.

Get-MgUserOwnedDevice -UserId user@domain.com -Property DisplayName,ApproximateLastSignInDateTime | 
  Sort-Object ApproximateLastSignInDateTime

I don't have any ownedDevices in my org, so you may need to find the correct property names

Related