Forum Discussion

dmarquesgn's avatar
dmarquesgn
Iron Contributor
Aug 20, 2024

Use powershell to add a tag to a MS Defender device

Hi,

 

I'm automating some security tasks with the help of powershell. One of the things I'm trying to automate now is the creation of a tag on a Defender device, but didn't found much info about it.

Anyone sucessfully added tags to Defender devices using powershell?

 

Thanks

 
 
  • jbmartin6's avatar
    jbmartin6
    Iron Contributor

    yes, the API for this is straightforward enough, it allows add or remove a tag via POST request

     

    $API = "machines/" + $DeviceId + "/tags"
    
    $Body = @{"Value"=$Tag;"Action"="$Action"}
    $Body = $Body | ConvertTo-Json
    
    

    ,  

    • dmarquesgn's avatar
      dmarquesgn
      Iron Contributor

      jbmartin6 

      Thanks for the tip. I was already able to do a part of the job, which is extracting the "machineid" from Defender, with this code:

      $apiUrl = "https://api-eu.securitycenter.microsoft.com/api/machines?`$filter=computerDnsName eq '$hostname'"
      $response = Invoke-RestMethod -Method Get -Uri $apiUrl -Headers $headers
      $machineId = $response.value[0].id

      And it's fine as I got the "machineid". But then I'm using this code for the addition of the tag.

      $Tag = "tag-test"
      $apiUrl = "https://api-eu.securitycenter.microsoft.com/api/machines/$machineId/tags"
      $Body = @{"Value"=$Tag;"Action"="Add"}
      $Body = $Body | ConvertTo-Json
      $response = Invoke-RestMethod -Method Post -Headers $headers -Body $body -Uri $apiUrl

      And I've got the error:

      "code": "Unauthorized",
      "message": "Invalid Authorization payload."

      But on the api permissions I've added the permissions which are written on the documentation, which are "Machine.ReadWriteAll" and "Machine.ReadWrite".

      Is there any way I can try to debug why doesn't this session has the permission to write the tag?

       

      Thanks

       

       

      • jbmartin6's avatar
        jbmartin6
        Iron Contributor
        You could double check using the MDE API explorer, but that won't help if the issue really is in the authorization header or token.

Resources