[SOLVED] Cannot parse url string for Microsoft graph because using the Invoke-MSGraphRequest command and query parameters


I cannot parse and make a call using the current URL because when I use the $filter and $select query parameters it breaks the string, yet it works great in Postman and give me all the data I needed.

Invoke-MSGraphRequest -Url "https://graph.microsoft.com/beta/deviceManagement/managedDevices?$select=emailaddress,id,imei,operatingSystem,ownerType,managedDeviceOwnerType&$filter=(operatingSystem eq 'iOS')" -HttpMethod GET

I need to filter these devices then if the ownership is personal, I was going to use graph API again to Update the object device using PATCH. Please help with this



The immediate solution to your problem is to simply escape the verbatim $‘s with a backtick `:

Invoke-MSGraphRequest -Url "https://graph.microsoft.com/beta/deviceManagement/managedDevices?`$select=emailaddress,id,imei,operatingSystem,ownerType,managedDeviceOwnerType&`$filter=(operatingSystem eq 'iOS')" -HttpMethod GET

Or to use single-quotes ' to avoid PowerShell attempting to expand what looks like variables – literal single-quotes inside the URL will have to be escaped by doubling them:

Invoke-MSGraphRequest -Url 'https://graph.microsoft.com/beta/deviceManagement/managedDevices?$select=emailaddress,id,imei,operatingSystem,ownerType,managedDeviceOwnerType&$filter=(operatingSystem eq ''iOS'')' -HttpMethod GET

That being said, I’d personally recommend constructing the query parameters from simpler parts:

$endpointURL = 'https://graph.microsoft.com/beta/deviceManagement/managedDevices'

# assign variable parts of the filter to a variable
$targetOperatingSystem = 'iOS'

# construct a hashtable containing all the query parameters
$GraphParameters = [ordered]@{
  '$select' = 'emailaddress,id,imei,operatingSystem,ownerType,managedDeviceOwnerType'
  '$filter' = "(operatingSystem eq '$targetOperatingSystem')"

# construct query string and final URL from the individual parts above
$queryString = $GraphParameters.GetEnumerator().ForEach({ $_.Key,$_.Value -join '=' }) -join '&'
$URL = $endpointURL,$queryString -join '?'

And then finally invoke Invoke-MSGraphRequest -Url $URL -HttpMethod Get

Answered By – Mathias R. Jessen

Answer Checked By – David Marino (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *