我需要从
lastsignindatetime
返回 signinactivity
对于使用 microsoft graph api 存储在 csv 文件中的特定用户。注意到 graph api explorer 和 PowerShell 的两个奇怪行为,这已成为正确检索数据的挑战。
https://graph.microsoft.com/beta/users/7d32b8e5-1bbc-414b-a9ce-afa743fb8753?$select=signInActivity
当我使用 PowerShell 脚本发出请求时,出现以下错误,尝试在问号和选择之间放置波浪号,但仍然返回相同的错误
$signInActivityUri = Invoke-RestMethod -Uri "https://graph.microsoft.com/beta/users/$userId?`$select=signInActivity"
$userId
变量已分配但未使用警告。这是一个错误警告,因为在 $userId
请求端点中使用了 $signInActivityUri
。我的应用程序注册已分配 directory.read.all and auditlog.Read.all
权限。我可以获得帮助以了解问题所在吗?
这是脚本
# Set your authentication details
$appId = ""
$appSecret = ""
$tenantId = ""
$authEndpoint = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token"
$body = @{
client_id = $appId
client_secret = $appSecret
scope = "https://graph.microsoft.com/.default"
grant_type = "client_credentials"
}
# Obtain access token
$tokenResponse = Invoke-RestMethod -Method Post -Uri $authEndpoint -Body $body
$accessToken = $tokenResponse.access_token
$requestHeaders = @{
'Authorization' = "Bearer $($accessToken)"
'Accept' = 'application/json'
}
$csvContent = Import-Csv -Path "C:\temp\users.csv"
foreach ($memberUser in $csvContent) {
# Get user information
$member = $memberUser.userPrincipalName
$userResponse = Invoke-RestMethod -Uri "https://graph.microsoft.com/v1.0/users?$filter=userPrincipalName eq '$member'&$select=userPrincipalName, id, displayName" -Headers $requestHeaders -Method Get
foreach ($user in $userResponse.value) {
$userId = $user.id
$signInActivityUri = Invoke-RestMethod -Uri "https://graph.microsoft.com/beta/users/$userId?$select=signInActivity" -Headers $requestHeaders -Method Get
$lastSignInDateTime = $signInActivityUri.signInActivity.lastSignInDateTime
$lastSignInDateTime
}
}
在我的 csv 中,我只有两个用户帐户 userprincipalnames
在第二个屏幕截图中,语法突出显示显示
$filter
和 $select
被解释为变量而不是文字,这就是失败的原因,您需要使用反引号 $
转义 `
。
另一个问题是
?
之后的 $userId
,它被解释为变量名称的一部分,在这种情况下您需要使用 ${...}
,并且再次,$select
必须用 转义`
:
foreach ($memberUser in $csvContent) {
# Get user information
$member = $memberUser.userPrincipalName
$userResponse = Invoke-RestMethod -Uri "https://graph.microsoft.com/beta/users?`$filter=userPrincipalName eq '$member'&`$select=userPrincipalName, id, displayName" -Headers $requestHeaders -Method Get
foreach ($user in $userResponse.value) {
$userId = $user.id
$signInActivityUri = Invoke-RestMethod -Uri "https://graph.microsoft.com/beta/users/${userId}?`$select=signInActivity" -Headers $requestHeaders -Method Get
$lastSignInDateTime = $signInActivityUri.signInActivity.lastSignInDateTime
$lastSignInDateTime
}
}