Gacrux
Gacrux

Reputation: 33

Unable to add device to group in Entra ID using Graph through Powershell script

I have a Powershell script which I created with the purpose of adding Intune devices to a Entra ID Security Group based on app presence on the device. It detects the application through a reg key and then adds that device to a specific security group using Graph API.

However, when I run the script, it does the detection fine, is able to get the device info but then errors out when trying to add the device to the security group and I am unable to figure out why, my knowledge using Graph in PS is also quite limited so I'm not very used to the syntax.

Run this block of code and expect the device to be added to the group, I have now escaped the $ref as was mentioned before but now I get a different error

# Function to add device to security group
function Add-DeviceToGroup {
    param (
        [string]$DeviceID
    )
    $token = Get-GraphToken
    $headers = @{ Authorization = "Bearer $token"; "Content-Type" = "application/json" }
    
    $body = @{
        "@odata.id" = "https://graph.microsoft.com/v1.0/devices/$DeviceID"
    } | ConvertTo-Json -Depth 2

    $url = "https://graph.microsoft.com/v1.0/groups/$SecurityGroupID/members/'$ref"
    $response = Invoke-RestMethod -Method Post -Uri $url -Headers $headers -Body $body

    Write-Host "Device successfully added to security group." -ForegroundColor Green
}

But I get the error 405 Method Not Allowed, using Fiddler it gives me more info saying:

{"error":{"code":"Request_BadRequest","message":"Specified HTTP method is not allowed for the request target'

Anyone able to assist or provide some insight into this?

Many thanks!

Upvotes: 2

Views: 57

Answers (1)

user2250152
user2250152

Reputation: 20758

I think you need to escape $ in $ref

$url = "https://graph.microsoft.com/v1.0/groups/$SecurityGroupID/members/`$ref"

Upvotes: 2

Related Questions