Skip to content

Instantly share code, notes, and snippets.

@RylandDeGregory
Created March 21, 2023 15:40
Show Gist options
  • Save RylandDeGregory/67fa1ca9d75e15a967a4ffa6130bc45c to your computer and use it in GitHub Desktop.
Save RylandDeGregory/67fa1ca9d75e15a967a4ffa6130bc45c to your computer and use it in GitHub Desktop.
Add custom event to Azure Event Hub using PowerShell
[Reflection.Assembly]::LoadWithPartialName('System.Web') | Out-Null
$HMAC = New-Object System.Security.Cryptography.HMACSHA256
$EventHubsNamespace = ''
$EventHubName = ''
$EventHubEndpoint = "$EventHubsNamespace.servicebus.windows.net/$EventHubName"
$AccessPolicyName = 'RootManageSharedAccessKey'
$AccessPolicyKey = ''
$SASExpirationTime = ([DateTimeOffset]::Now.ToUnixTimeSeconds()) + 3000
$SignatureString = [System.Web.HttpUtility]::UrlEncode($EventHubEndpoint) + "`n" + [string]$SASExpirationTime
$HMAC.Key = [Text.Encoding]::ASCII.GetBytes($AccessPolicyKey)
$Signature = [Convert]::ToBase64String($HMAC.ComputeHash([Text.Encoding]::ASCII.GetBytes($SignatureString)))
$SASToken = 'SharedAccessSignature sr=' + [System.Web.HttpUtility]::UrlEncode($EventHubEndpoint) + '&sig=' + [System.Web.HttpUtility]::UrlEncode($Signature) + '&se=' + $SASExpirationTime + '&skn=' + $AccessPolicyName
$Headers = @{
'Authorization' = $SASToken;
'Content-Type' = 'application/atom+xml;type=entry;charset=utf-8';
}
$RestUri = "https://$EventHubEndpoint/messages"
# Body contains a sample JSON object
$Body = @{
DeviceId = 'dev-01'
Temperature = 37
Elements = @(
'hot'
'cold'
)
} | ConvertTo-Json
Invoke-RestMethod -Uri $RestUri -Method Post -Headers $Headers -Body $Body
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment