Quick Code – Send Events to an Event Hub with PowerShell

Here is another quick one – let’s send events to an event hub with PowerShell!

function New-SasToken {
    param(
        [string]$ResourceUri,
        [string]$Key,
        [string]$PolicyName,
        [timespan]$TokenTimeToLive
    )

    $Expires = [DateTimeOffset]::Now.Add($TokenTimeToLive).ToUnixTimeSeconds()
    $StringToSign = [System.Web.HttpUtility]::UrlEncode($ResourceUri) + "`n" + $Expires
    $HMACSHA256 = New-Object System.Security.Cryptography.HMACSHA256
    $HMACSHA256.Key = [Text.Encoding]::UTF8.GetBytes($Key)
    $Signature = $HMACSHA256.ComputeHash([Text.Encoding]::UTF8.GetBytes($StringToSign))
    $Signature = [Convert]::ToBase64String($Signature)
    $Token = "SharedAccessSignature sr=" + [System.Web.HttpUtility]::UrlEncode($ResourceUri) + "&sig=" + [System.Web.HttpUtility]::UrlEncode($Signature) + "&se=" + $Expires + "&skn=" + $PolicyName
    return $Token
}

# Event Hub parameters
$namespace = "yourNamespace"
$eventHubName = "yourEventHubName"
$sharedAccessKeyName = "yourSharedAccessKeyName"
$sharedAccessKey = "yourSharedAccessKey"
$endpoint = "https://$namespace.servicebus.windows.net/$eventHubName/messages"
$tokenTimeToLive = New-TimeSpan -Minutes 60

# Generate SAS token
$sasToken = New-SasToken -ResourceUri $endpoint -Key $sharedAccessKey -PolicyName $sharedAccessKeyName -TokenTimeToLive $tokenTimeToLive

# Event data
$body = @"
{
    "Data": "Sample Event Data"
}
"@

# Send the event
$headers = @{
    "Authorization" = $sasToken
    "Content-Type" = "application/json"
}

try {
    $response = Invoke-RestMethod -Uri $endpoint -Method Post -Body $body -Headers $headers
    Write-Output "Event sent successfully"
}
catch {
    Write-Error "Failed to send event: $_"
}