👋

PowerShellからTeams通知:WebhookからPowerAutomateへの移行

に公開

動機

私のチームではCIのエラー通知をTeamsのWebhookを使って通知するようにしていたのですが、Incoming Webhookが廃止になるとの情報がありPowerAutomateを使った方法に変更しました。

https://devblogs.microsoft.com/microsoft365dev/retirement-of-office-365-connectors-within-microsoft-teams/

概要

検証環境

Windows11
Windows PowerShell 5.1

前提条件

  • PowerShellScriptからWebhookを使ってTeamsに通知している

今回やること

  • Incoming WebhookからPowerAutomateに移行する

移行作業

  • PowerAutomateでワークフローを作成する
  • PowerShellScriptを作成

PowerAutomateでワークフローを作成する

「Webhook要求を受信するとチャンネルに投稿する」というテンプレートがあるので、それを利用してワークフローを作成する。

投稿先は、チャンネル以外にもグループチャットにも投稿することができます。

PowerShellScriptを作成

アダプティブカードを使用します。
https://learn.microsoft.com/ja-jp/microsoftteams/platform/webhooks-and-connectors/how-to/connectors-using?tabs=cURL%2Ctext1

# PowerAutomateで取得したwebhook
# 環境変数から取得
$webhookUrl = $env:WEBHOOK_URL

$text = "Hello world"

$body = @{
    type        = "message"
    attachments = @(
        @{
            contentType = "application/vnd.microsoft.card.adaptive"
            contentUrl  = $null
            content     = @{
                "$schema" = "http://adaptivecards.io/schemas/adaptive-card.json"
                type      = "AdaptiveCard"
                version   = "1.4"
                body      = @(
                    @{
                        type = "TextBlock"
                        text = $text
                    }
                )
            }
        }
    )
} | ConvertTo-Json -Depth 6

Invoke-WebRequest -Uri $webhookUrl -Method Post -ContentType "application/json; charset=utf-8" -Body $body

WebhookURLはPowerAutomateで作成したフローから取得することが出来ます。

通知はこのような感じです。

詰まったこと

日本語の文字化け対応

Invoke-WebRequestでwebhookを呼び出す時に文字コードを設定しないと日本語が文字化けします。

改行コードが認識されない

マイクロソフトの公式には、`nが改行コードと記載されていますが、認識されなかったので代わりに以下のコードを使います。

$text = "Hello world `r `n Good Night"

Discussion