Skip to content

Event Grid

Handle discrete events from Azure services and custom topics with Event Grid triggers in PowerShell.

Event Grid Trigger

function.json:

{
  "bindings": [
    {
      "name": "EventGridEvent",
      "type": "eventGridTrigger",
      "direction": "in"
    }
  ]
}

run.ps1:

param($EventGridEvent, $TriggerMetadata)

Write-Information "Event type: $($EventGridEvent.eventType)"
Write-Information "Subject: $($EventGridEvent.subject)"
Write-Information "Data: $($EventGridEvent.data | ConvertTo-Json -Compress)"

Event Grid delivers a single event per invocation. The runtime handles the subscription validation handshake automatically for the Event Grid schema.

Routing by Event Type

switch ($EventGridEvent.eventType) {
    "Microsoft.Storage.BlobCreated" {
        Write-Information "New blob: $($EventGridEvent.data.url)"
    }
    "Microsoft.Storage.BlobDeleted" {
        Write-Information "Blob removed: $($EventGridEvent.data.url)"
    }
    default {
        Write-Information "Unhandled event type"
    }
}

Output Binding

Publish events to a custom topic:

{
  "name": "OutputEvent",
  "type": "eventGrid",
  "direction": "out",
  "topicEndpointUri": "EventGridTopicEndpoint",
  "topicKeySetting": "EventGridTopicKey"
}
Push-OutputBinding -Name OutputEvent -Value @{
    id        = [guid]::NewGuid().ToString()
    subject   = "orders/created"
    eventType = "Contoso.Order.Created"
    eventTime = (Get-Date).ToUniversalTime().ToString("o")
    data      = @{ orderId = 1234 }
}

Event Grid vs Event Hubs

Use Event Grid for reactive, discrete event handling and Event Hubs for high-throughput streaming. See Event Hubs.

See Also

Sources