Send Chat Message to a Teams Channel with PowerShell and MS GRAPH API

The next Post in my GRAPH API Series now switches to Microsoft Teams. Let us send a Chat Message to a Teams Channel.

To learn more from Microsoft GRAPH API, see my Blog Series:
Part 1 – Authentication and Azure App – Use Microsoft Graph API with PowerShell – Part 1 » TechGuy
Part 2 – Oauth2.0 – Use Microsoft Graph API with PowerShell – Part 2 » TechGuy
Part 3 – First Powershell Script to get a Teams List and Walkthrough – Use Microsoft Graph API with PowerShell – Part 3 » TechGuy
Part 4 – Some Examples – Use Microsoft Graph API with PowerShell – Part 4 » TechGuy

API Reference and Permissions

Let see the following Docs for more Details.

In this case, we are using Delegated Permissions, so you have to create a User and add the User as a Team Member.

The Script

$clientID = "your ID"
$User="your User"
$PW="your PW"
$resource = "https://graph.microsoft.com"

$TeamName="Techguy Team"
$ChannelName="Testing Channel"


#Connect to GRAPH API
$tokenBody = @{  
    Grant_Type = "password"  
    Scope      = "user.read%20openid%20profile%20offline_access"  
    Client_Id  = $clientId  
    username   =  $User
    password   = $pw
    resource  = $resource
}   

$tokenResponse = Invoke-RestMethod "https://login.microsoftonline.com/common/oauth2/token" -Method Post -ContentType "application/x-www-form-urlencoded" -Body $tokenBody -ErrorAction STOP
$headers = @{
    "Authorization" = "Bearer $($tokenResponse.access_token)"
    "Content-type"  = "application/json"
}



#Get ID for the Team
$URLgetteamid="https://graph.microsoft.com/v1.0/groups?$select=id,resourceProvisioningOptions"
$TeamID=((Invoke-RestMethod -Method GET -Uri $URLgetteamid  -Headers $headers).value | Where-Object -property displayName -value $TeamName -eq).id


#Get ID for the Channel
$URLgetchannelid="https://graph.microsoft.com/v1.0/teams/$TeamID/channels"
$ChannelID=((Invoke-RestMethod -Method GET -Uri $URLgetchannelid  -Headers $headers).value | Where-Object -property displayName -value $ChannelName -eq).id



#Send Message in channel
$URLchatmessage="https://graph.microsoft.com/v1.0/teams/$TeamID/channels/$ChannelID/messages"
$BodyJsonTeam = @"
            
                {
                    "body": {
                      "content": "Hello World"
                    }
                  }
            
"@


Invoke-RestMethod -Method POST -Uri $URLchatmessage -Body $BodyJsonTeam -Headers $headers

The Result

In Teams Channel, we see the following Result.

GitHub Repo

Here you can find the GitHub Repo with a lot of other examples: Seidlm/Microsoft-Graph-API-Examples (github.com)

Michael Seidl aka Techguy
au2mate everything

Leave a Comment

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

*