Power Shell script to send a simple JSON to an Azure Event Hub

Until now, I’ve always used a C# program provided to me to send events to an Azure Event Hub. This actually became a bit too heavy-duty for me over time. So I looked for a PowerShell alternative, but couldn’t really find one at first, possibly because I wanted to learn it myself…

The goal of the whole thing was to send events as JSON to an Azure Event Hub to process this data in Fabric Real Time.

Here you can find the finished script, which is partly based on information from here, and partly I’ve supplemented it:

https://learn.microsoft.com/en-us/rest/api/eventhub/generate-sas-token#code-try-8

Here you can find the complete script, where the information for the Azure Event Hub still needs to be added:

[Reflection.Assembly]::LoadWithPartialName("System.Web")| out-null
$URI="<Event Hubs Namespace>.servicebus.windows.net/<Event Hub>"
$Access_Policy_Name="<Shared access policies>"
$Access_Policy_Key="<Key>"
#Token expires now+300
$Expires=([DateTimeOffset]::Now.ToUnixTimeSeconds())+1800
$SignatureString=[System.Web.HttpUtility]::UrlEncode($URI)+ "`n" + [string]$Expires
$HMAC = New-Object System.Security.Cryptography.HMACSHA256
$HMAC.key = [Text.Encoding]::ASCII.GetBytes($Access_Policy_Key)
$Signature = $HMAC.ComputeHash([Text.Encoding]::ASCII.GetBytes($SignatureString))
$Signature = [Convert]::ToBase64String($Signature)
$SASToken = "SharedAccessSignature sr=" + [System.Web.HttpUtility]::UrlEncode($URI) + "&sig=" + [System.Web.HttpUtility]::UrlEncode($Signature) + "&se=" + $Expires + "&skn=" + $Access_Policy_Name

    $payload = @{
        msg  = "GDFJHZSHJK"
        time = (Get-Date).ToString("o")
    }
    $json = $payload | ConvertTo-Json -Compress

$endpoint = "https://$URI/messages?timeout=60&api-version=2014-01"
$headers  = @{
    "Authorization" = $SASToken
    "Content-Type"  = "application/json; charset=utf-8"
}

Invoke-RestMethod -Uri $endpoint -Method Post -Headers $headers -Body $json

When the script is running, you will see corresponding data like this coming in on the monitor:

I will explain how to proceed in Microsoft Fabric in the coming blog posts.

Categorized: Allgemein

Comments are closed.