Редагувати

Поділитися через


Subscribe to events for an Azure subscription with PowerShell

This script creates an Event Grid subscription to the events for an Azure subscription.

If you don't have an Azure subscription, create an Azure free account before you begin.

Sample script - stable

Note

We recommend that you use the Azure Az PowerShell module to interact with Azure. To get started, see Install Azure PowerShell. To learn how to migrate to the Az PowerShell module, see Migrate Azure PowerShell from AzureRM to Az.

# Provide an endpoint for handling the events. Must be formatted "https://your-endpoint-URL"
$myEndpoint = "<your-endpoint-URL>"

# Select the Azure subscription you want to subscribe to. You need this command only if the 
# current subscription is not the one you wish to subscribe to.
Set-AzContext -Subscription "<subscription-name-or-ID>"

# Subscribe to the Azure subscription. The command creates the subscription for the currently selected Azure subscription. 
New-AzEventGridSubscription -Endpoint $myEndpoint -EventSubscriptionName demoSubscriptionToAzureSub

Sample script - preview module

This preview sample script requires the Event Grid module. To install, run Install-Module -Name AzureRM.EventGrid -AllowPrerelease -Force -Repository PSGallery

Important

Using this Azure feature from PowerShell requires the AzureRM module installed. This is an older module only available for Windows PowerShell 5.1 that no longer receives new features. The Az and AzureRM modules are not compatible when installed for the same versions of PowerShell. If you need both versions:

  1. Uninstall the Az module from a PowerShell 5.1 session.
  2. Install the AzureRM module from a PowerShell 5.1 session.
  3. Download and install PowerShell Core 6.x or later.
  4. Install the Az module in a PowerShell Core session.
# You must have the latest version of the Event Grid PowerShell module.
# To install:
# Install-Module -Name AzureRM.EventGrid -AllowPrerelease -Force -Repository PSGallery

# Provide an endpoint for handling the events. Must be formatted "https://your-endpoint-URL"
$myEndpoint = "<your-endpoint-URL>"

# Get the subscription ID
$subID = (Get-AzureRmSubscription -SubscriptionName "<subscription-name>").Id

# Subscribe to the Azure subscription. The command creates the subscription for the currently selected Azure subscription. 
New-AzureRmEventGridSubscription -ResourceId "/subscriptions/$subID" -Endpoint $myEndpoint -EventSubscriptionName demoSubscriptionToAzureSub

Script explanation

This script uses the following command to create the event subscription. Each command in the table links to command-specific documentation.

Command Notes
New-AzEventGridSubscription Create an Event Grid subscription.

Next steps