Search code examples
azurepowershellgraph

Using $filter through Microsoft graph API request


I'm trying to use MS graph API via a small Powershell script as described here https://learn.microsoft.com/en-us/graph/api/riskyusers-list?view=graph-rest-beta&tabs=http this filter doesn't give any result and if I remove it it works but do not give the complete list (only few results)

$ApplicationID = "45xxxxxxxx"
$TenatDomainName = "2a3xxxxx"
$AccessSecret = Read-Host "Enter Secret"

$Body = @{    
Grant_Type    = "client_credentials"
Scope         = "https://graph.microsoft.com/.default"
client_Id     = $ApplicationID
Client_Secret = $AccessSecret
} 

$ConnectGraph = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$TenatDomainName/oauth2/v2.0/token" -Method POST -Body $Body

$token = $ConnectGraph.access_token

#$GrapRisk = "https://graph.microsoft.com/v1.0/identityProtection/riskyUsers"
$GrapRisk = "https://graph.microsoft.com/beta/identityProtection/riskyUsers?$filter=riskLevel eq microsoft.graph.riskLevel'medium'"


$riskyList= (Invoke-RestMethod -Headers @{Authorization = "Bearer $($token)"} -Uri $GrapRisk -Method Get).value |select userPrincipalName, riskState, riskLastUpdatedDateTime, riskLevel

$riskyList

I execute this script through Powershell ISE but even with curl and terminal I cannot use the filter parameter. Thanks


Solution

  • Whenever a string literal uses double-quotes ("'s), PowerShell interprets it as expandable, meaning PowerShell will attempt to resolve and expand variable expressions (like $filter) when evaluating the string.

    Use a backtick (`) to escape the $, and it should work:

    $GrapRisk = "https://graph.microsoft.com/beta/identityProtection/riskyUsers?`$filter=riskLevel eq microsoft.graph.riskLevel'medium'"
    

    For more details about the semantics of different types of string literals in PowerShell, read the about_Quoting_Rules help topic