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

PowerShell按日期排序JSON数据:获取用户最新登录设备遇阻

问题:使用Microsoft Graph API按登录时间排序用户设备失败

我正在使用Microsoft Graph API,尝试按Last Signin Date对用户设备进行排序。目前已成功针对用户查询API,并通过ConvertFrom-Json将结果转换为可遍历的自定义对象,但无法从列表中获取最新登录的设备。我尝试使用Sort-Object,但该代码似乎未生效,恳请提供建议或指导!

我的代码如下:

### 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

解决方案

你的Sort-Object用法存在错误,导致排序失效。以下是修正后的代码及说明:

修正后的核心代码

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

# 提取设备数组并按登录时间降序排序
$deviceList = ($jsonWebData.content | ConvertFrom-Json).value | Sort-Object -Property approximateLastSignInDateTime -Descending

# 输出所有设备的登录时间(已排序)
$deviceList.approximateLastSignInDateTime

# 获取最新登录的设备
$latestDevice = $deviceList[0]
$latestDevice

错误原因及说明

  1. 属性引用错误:原代码中Sort-Object -Property ($_.value.approximateLastSignInDateTime)的写法无效,因为$_在当前上下文没有指代任何对象,Sort-Object无法识别要排序的属性。
  2. 数据结构处理错误:Graph API返回的结果中,设备数据都包含在value数组里,需要先提取这个数组再进行排序操作。
  3. 排序方向:添加-Descending参数可以让最新的登录时间排在数组最前面,直接取第一个元素就能得到最新登录的设备。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 08:09:16