Running PowerShell from a Logic App

Hola! Today let’s look at a simple way to get PowerShell scripts to run from a Logic App. It will involve a single extra tool, but this really adds versatility to an already versatile tool.

Start by creating a PowerShell script for your specific task. This script will be uploaded to an Azure Automation Runbook. For instance, if you aim to manage VMs, ensure the script includes Azure RM or Az module commands to start, stop, or monitor VM states. Here is an example:

# Sample PowerShell Script to Start a Specific Azure VM

Connect-AzAccount -Identity
Start-AzVM -Name $vmName -ResourceGroupName $resourceGroupName

Obviously this is a short script that we can do with just Logic Apps (and not involve pwsh at all), but you get the point.

Now – Upload and publish your PowerShell script in an Azure Automation Runbook.

  1. In your Azure Automation Account, create a new Runbook.
  2. Choose “PowerShell” as the Runbook type.
  3. Import your script and publish the Runbook.

Go ahead test the runbook if you want.

Next – create a Logic App to trigger the Runbook. You might use a schedule, an HTTP request, or another event in Azure as a trigger.

  1. In the Logic App Designer, add a new step and search for the “Azure Automation” connector.
  2. Select “Create job” action.
  3. Fill in the necessary details: Automation Account, Runbook Name, and parameters (if your script requires them). In our example we might dynamically pass the VM name, or maybe look for only VMs that are off and loop through them.

For more complex scenarios, you might need to integrate with other Azure services before or after executing your PowerShell script:

  • Azure Functions: For custom logic that cannot be implemented directly in PowerShell or needs a specific runtime environment.
  • Azure Event Grid: To trigger your Logic App based on events from various Azure services.
  • Azure Monitor: To analyze logs and metrics from your Logic App and Automation Runbooks, enabling proactive management and optimization of your automated tasks.

And there you go! Go put PowerShell everywhere!

Quick Code – Install AMA and Assign a DCR with PowerShell

Happy Holidays! Here’s a quick post to share some code that will inventory Azure VMs, install the AMA if necessary, and then assign a DCR to the VM.

# Ensure you're logged in to Azure

# Define the Data Collection Rule (DCR) resource ID
$dcrResourceId = "<Your-DCR-Resource-ID>"

# Get all VMs in the subscription
$vms = Get-AzVM

# Use ForEach-Object with -Parallel to process VMs concurrently
$vms | ForEach-Object -Parallel {
    $vm = $_
    $osType = $vm.StorageProfile.OsDisk.OsType
    $extensionName = if ($osType -eq "Windows") { "AzureMonitorWindowsAgent" } else { "AzureMonitorLinuxAgent" }
    $extensionPublisher = "Microsoft.Azure.Monitor"
    $vmResourceId = "/subscriptions/$using:vm.SubscriptionId/resourceGroups/$using:vm.ResourceGroupName/providers/Microsoft.Compute/virtualMachines/$using:vm.Name"

    try {
        # Check if the Azure Monitor Agent extension is installed
        $amaExtension = Get-AzVMExtension -ResourceGroupName $using:vm.ResourceGroupName -VMName $using:vm.Name -Name $extensionName -ErrorAction SilentlyContinue

        if (-not $amaExtension) {
            try {
                # Install the Azure Monitor Agent extension
                Set-AzVMExtension -ResourceGroupName $using:vm.ResourceGroupName -VMName $using:vm.Name -Name $extensionName -Publisher $extensionPublisher -ExtensionType $extensionName -TypeHandlerVersion "1.0" -Location $using:vm.Location
                Write-Host "Installed Azure Monitor Agent on $($using:vm.Name)"
            } catch {
                Write-Host "Failed to install Azure Monitor Agent on $($using:vm.Name): $_"
        } else {
            Write-Host "Azure Monitor Agent is already installed on $($using:vm.Name)"
    } catch {
        Write-Host "Error checking Azure Monitor Agent on $($using:vm.Name): $_"

    try {
        # Assign the DCR to the VM
        $settings = @{ "dataCollectionRuleResourceIds" = @($using:dcrResourceId) }
        Set-AzVMExtension -ResourceGroupName $using:vm.ResourceGroupName -VMName $using:vm.Name -Name "AzureMonitorVmExtension" -Publisher $extensionPublisher -ExtensionType $extensionName -Settings $settings -Location $using:vm.Location
        Write-Host "Assigned DCR to $($using:vm.Name)"
    } catch {
        Write-Host "Failed to assign DCR to $($using:vm.Name): $_"
} -ThrottleLimit 5 # Adjust the ThrottleLimit as necessary

Setting up Azure OpenAI with PowerShell

If haven’t been living under a rock, you know that Azure OpenAI is a powerful tool that brings the cutting-edge capabilities of OpenAI’s models to the cloud, offering scalability, reliability, and integration with Azure’s vast ecosystem.

Because I am who I am we will use PowerShell to setup our Azure OpenAI instance. Whether you’re automating deployment or integrating Azure OpenAI into your existing infrastructure, PowerShell scripts can simplify the process. Let’s get started with a step-by-step guide to setting up your Azure OpenAI instance using PowerShell.


Before we dive into the commands, ensure you have the following:

  • An Azure subscription. If you don’t have one, you can create a free account.
  • PowerShell installed on your system. If you’re on Windows, you’re probably already set. For Mac and Linux users, check out PowerShell Core.
  • The Azure PowerShell module installed. You can install it by running Install-Module -Name Az -AllowClobber -Scope CurrentUser in your PowerShell terminal.

Step 1: Log in to Azure

First things first, let’s log into Azure. Open your PowerShell terminal and run:


This command opens a login window where you can enter your Azure credentials. Once authenticated, you’re ready to proceed.

Step 2: Create a Resource Group

Azure OpenAI instances need to reside in a resource group, a container that holds related resources for an Azure solution. To create a new resource group, use:

New-AzResourceGroup -Name 'MyResourceGroup' -Location 'EastUS'

Replace 'MyResourceGroup' with your desired resource group name and 'EastUS' with your preferred location.

Step 3: Register the OpenAI Resource Provider

Before deploying Azure OpenAI, ensure your subscription is registered to use the OpenAI resource provider. Register it with:


Register-AzResourceProvider -ProviderNamespace 'Microsoft.OpenAI'

This command might take a few minutes. To check the status, you can run Get-AzResourceProvider -ProviderNamespace 'Microsoft.OpenAI'.

Step 4: Create an Azure OpenAI Instance

Now, the exciting part—creating your Azure OpenAI instance. Use the following command:


New-AzResource -ResourceGroupName 'MyResourceGroup' -ResourceType 'Microsoft.OpenAI/workspaces' -Name 'MyOpenAIInstance' -Location 'EastUS' -PropertyObject @{ sku = 'S0'; properties = @{ description = 'My Azure OpenAI instance for cool AI projects'; } }

Make sure to replace 'MyResourceGroup', 'MyOpenAIInstance', and 'EastUS' with your resource group name, desired OpenAI instance name, and location, respectively.

Step 5: Confirm Your Azure OpenAI Instance

To ensure everything went smoothly, you can list all OpenAI instances in your resource group:


Get-AzResource -ResourceGroupName 'MyResourceGroup' -ResourceType 'Microsoft.OpenAI/workspaces'

This command returns details about the OpenAI instances in your specified resource group, confirming the successful creation of your instance. Enjoy your brand new OpenAI instance!

Quick Dive: Integrating Logic Apps with Azure OpenAI

Let’s cut to the chase: Integrating Azure Logic Apps with Azure OpenAI unlocks a plethora of possibilities, from automating content creation to enhancing data analysis. Below is a step-by-step guide to melding these powerful tools.

Step 1: Set Up Azure OpenAI

First, you need an Azure OpenAI service instance. Go to the Azure Portal, search for Azure OpenAI Service, and create a new instance. Once deployed, grab your API key and endpoint URL from the resource management section.

Step 2: Create Your Logic App

Navigate back to the Azure Portal and create a new Logic App:

  • Choose your subscription and resource group.
  • Pick a region close to you for lower latency.
  • Name your Logic App.
  • Click “Review + create” and then “Create” after validation passes.

Step 3: Design Your Logic App Workflow

Once your Logic App is ready, it’s time to design the workflow:

  • Open your Logic App in the Azure Portal and go to the Logic App Designer.
  • Start with a common trigger like “When an HTTP request is received” if you want your Logic App to act based on external requests.
  • Add a new step by searching for “HTTP” in the actions list and choose the “HTTP – HTTP” action. This will be used to call the Azure OpenAI API.

Step 4: Configure the HTTP Action for Azure OpenAI

  • Method: POST
  • URI: Enter the endpoint URL of your Azure OpenAI service.
  • Headers: Add two headers:
    • Content-Type with the value application/json
    • Authorization with the value Bearer <Your Azure OpenAI API Key>
  • Body: Craft the JSON payload according to your task. For example, to generate text, your body might look like this:
  "prompt": "Write a brief about integrating Azure OpenAI with Logic Apps.",
  "temperature": 0.7,
  "max_tokens": 100

Step 5: Process the Response

After calling the Azure OpenAI API, you’ll want to handle the response:

  • Add a “Parse JSON” action to interpret the API response.
  • In the “Content” box, select the body of the HTTP action.
  • Define the schema based on the Azure OpenAI response format. For text generation, you’ll focus on extracting the generated text from the response.

Step 6: Add Final Actions

Decide what to do with the Azure OpenAI’s response. You could:

  • Send an email with the generated content.
  • Save the response to a database or a file in Azure Blob Storage.
  • Respond to the initial HTTP request with the generated content.

Step 7: Test Your Logic App

  • Save your Logic App and run a test by triggering it based on your chosen trigger method.
  • Monitor the run in the “Overview” section of your Logic App to ensure everything executes as expected.

Deploy Logic Apps with PowerShell

This post is basically just a way to refresh my memory when in the next 3 months I completely forget how easy this is. Here’s how you can leverage PowerShell to manage your Logic Apps and their connections more effectively.

# Define variables
$resourceGroupName = 'YourResourceGroup'
$logicAppName = 'YourLogicAppName'
$templateFilePath = 'path/to/your/template.json'
$parametersFilePath = 'path/to/your/parameters.json'

# Deploy the Logic App
New-AzResourceGroupDeployment -Name DeployLogicApp `
  -ResourceGroupName $resourceGroupName `
  -TemplateFile $templateFilePath `
  -TemplateParameterFile $parametersFilePath

If you need a template example or parameters example, check the end of this post!!

Managing Logic App Connections with PowerShell

PowerShell can also simplify the creation and management of Logic App connections, making it easier to connect to services like Office 365 or custom APIs:

# Creating a connection to Office 365
$connectionName = 'office365Connection'
$connectionParams = @{
    'token:TenantId' = '<YourTenantId>';
    'token:PrincipalId' = '<YourPrincipalId>';
    'token:ClientSecret' = '<YourClientSecret>'

New-AzResource -ResourceType 'Microsoft.Web/connections' -ResourceName $connectionName `
  -ResourceGroupName $resourceGroupName -Location 'eastus' `
  -Properties $connectionParams

Sample Template and Parameter Json Files:


  "$schema": "",
  "contentVersion": "",
  "resources": [
      "type": "Microsoft.Logic/workflows",
      "apiVersion": "2019-05-01",
      "name": "[parameters('logicAppName')]",
      "location": "[parameters('location')]",
      "properties": {
        "state": "Enabled",
        "definition": {
          "$schema": "",
          "contentVersion": "",
          "triggers": {
            "When_a_HTTP_request_is_received": {
              "type": "Request",
              "kind": "Http",
              "inputs": {
                "method": "POST",
                "schema": {}
          "actions": {
            "Send_an_email": {
              "type": "ApiConnection",
              "inputs": {
                "host": {
                  "connection": {
                    "name": "@parameters('$connections')['office365']['connectionId']"
                "method": "post",
                "body": {
                  "Subject": "Email Subject Here",
                  "Body": "<p>Email Body Here</p>",
                  "To": ""
                "path": "/Mail"
          "outputs": {}
        "parameters": {
          "$connections": {
            "defaultValue": {},
            "type": "Object"
  "parameters": {
    "logicAppName": {
      "defaultValue": "YourLogicAppName",
      "type": "String"
    "location": {
      "defaultValue": "eastus",
      "type": "String"


  "$schema": "",
  "contentVersion": "",
  "parameters": {
    "logicAppName": {
      "value": "YourLogicAppName"
    "location": {
      "value": "eastus"

Automating Azure Service Health Alerts with PowerShell

Hello, Azure amigos! Today we’re diving into the depths of automating Azure Service Health alerts using PowerShell.

What’s Azure Service Health Anyway?

Azure Service Health provides personalized alerts and guidance when Azure service issues affect you. It breaks down into three main types of alerts:

  • Service issues: Problems in Azure services that affect you right now.
  • Planned maintenance: Upcoming maintenance that can affect your services in the future.
  • Health advisories: Issues that require your attention but don’t directly impact Azure services (e.g., security vulnerabilities, deprecated features).

Now, onto the fun part—automating these alerts with PowerShell!


I’ll assume you’ve got the Azure PowerShell module installed and you’re familiar with the basics of PowerShell scripting and Azure. If not, it’s like assuming you can cook a gourmet meal without knowing how to turn on the stove—start there first!

Let’s get one more thing worked out – creating an action group to use in the Alert Rule.

$ActionGroupName = "MyActionGroup"
$ResourceGroupName = "MyResourceGroup"
$ShortName = "MyAG"

# Replace these values with your actual email and phone number
$Email = ""
$Sms = "+1-555-867-5309"

# Creating the action group
New-AzActionGroup -ResourceGroupName $ResourceGroupName -Name $ActionGroupName -ShortName $ShortName -EmailReceiver $Email -SmsReceiver $Sms -Location "Global"

With our action group ready, it’s time to define what we’re actually alerting on. We can create alerts for specific issues, maintenance events, or advisories. Here’s how:

# Assuming you've already created an action group as per the previous steps

$ResourceGroupName = "MyResourceGroup"
$RuleName = "MyServiceHealthAlert"
$ActionGroupId = (Get-AzActionGroup -ResourceGroupName $ResourceGroupName -Name "MyActionGroup").Id

# Service Health alert criteria
$criteria = New-AzActivityLogAlertCondition -Field 'category' -Equal 'ServiceHealth'

# Creating the Service Health alert
Set-AzActivityLogAlert -Location "Global" -Name $RuleName -ResourceGroupName $ResourceGroupName -Scope "/subscriptions/your-subscription-id" -Condition $criteria -ActionGroup $ActionGroupId

This PowerShell command creates an alert rule specifically for Service Health notifications within Azure. It triggers based on the ‘ServiceHealth’ category in the Azure Activity Log, ensuring you’re notified whenever there are relevant service health events affecting your subscription.


  • $criteria: This line defines what we’re alerting on. In this case, it’s any activity log entries with a category of ‘ServiceHealth’.
  • Set-AzActivityLogAlert: This cmdlet creates or updates an activity log alert rule. We specify the alert name, the scope (usually your subscription or a resource group), the conditions under which to trigger, and the action group to notify.

And there ya go! Simple and quick. Enjoy your new Alert Rule!

Optimizing Azure Cost Management with PowerShell

Let’s dig into some quick hits for trying to keep your costs down in Azure – and since I am who I am let’s use PowerShell

Automating Cost Reports

First – lets script the retrieval of usage and cost data, businesses can monitor their cloud expenditures closely, identify trends, and make informed decisions to optimize costs.

Get-AzConsumptionUsageDetail -StartDate "2023-01-01" -EndDate "2023-01-31" | Export-Csv -Path "./AzureCostsJan.csv"

This simple script fetches the consumption details for January 2023 and exports the data to a CSV file – from there you can use something like Excel to dig into your big costs.

Identifying Underutilized Resources

PowerShell scripts can scan Azure services to pinpoint underutilized resources, such as VMs with low CPU utilization or oversized and underused storage accounts, which are prime candidates for downsizing or deletion to cut costs.

Get-AzVM | ForEach-Object {
    $metrics = Get-AzMetric -ResourceId $_.Id -MetricName "Percentage CPU" -TimeGrain "00:05:00" -StartTime (Get-Date).AddDays(-30) -EndTime (Get-Date)
    $avgCpu = ($metrics.Data | Measure-Object -Property Average -Average).Average
    if ($avgCpu -lt 10) {
        Write-Output "$($_.Name) is underutilized."

This script assesses VMs for low CPU usage, identifying those with an average CPU utilization below 10% over the last 30 days.

Implementing Budget Alerts

Setting up budget alerts with PowerShell helps prevent unexpected overspending by notifying you when your costs approach predefined thresholds.

$budget = New-AzConsumptionBudget -Amount 1000 -Category Cost -TimeGrain Monthly -StartDate 2023-01-01 -EndDate 2023-12-31 -Name "MonthlyBudget" -NotificationKey "90PercentAlert" -NotificationThreshold 90 -ContactEmails ""

This script creates a monthly budget of $1000 and sets up an alert to notify specified contacts via email when 90% of the budget is consumed.

And there you go! Some quick and easy scripts to make sure you don’t blow your Azure budget!

Creating Alert Rules in Azure with AZ PowerShell – Some Samples

Let go over a simple one – how to create various types of alert rules in Azure using the AZ PowerShell Module.

Each example targets a different aspect of Azure monitoring, but doesn’t cover them all. Remember to tweak the parameters to match your environment.

Metric Alerts for Performance Monitoring

To keep an eye on Azure service metrics:

$criteria = New-AzMetricAlertRuleV2Criteria -MetricName 'Percentage CPU' -TimeAggregation Average -Operator GreaterThan -Threshold 80

Add-AzMetricAlertRuleV2 -Name 'HighCPUAlert' -ResourceGroupName 'YourResourceGroupName' -WindowSize 00:05:00 -Frequency 00:01:00 -TargetResourceId '/subscriptions/yourSubscriptionId/resourceGroups/yourResourceGroupName/providers/Microsoft.Compute/virtualMachines/yourVMName' -Condition $criteria -ActionGroup '/subscriptions/yourSubscriptionId/resourceGroups/yourResourceGroupName/providers/microsoft.insights/actionGroups/yourActionGroupName' -Severity 3 -Description 'Alert on high CPU usage.'

Log Alerts for Custom Log Queries

For alerts based on log analytics:

$query = "AzureActivity | where OperationName == 'Create or Update Virtual Machine' and ActivityStatus == 'Succeeded'"

Set-AzScheduledQueryRule -ResourceGroupName 'YourResourceGroupName' -Location 'East US' -ActionGroup '/subscriptions/yourSubscriptionId/resourceGroups/yourResourceGroupName/providers/microsoft.insights/actionGroups/yourActionGroupName' -ConditionQuery $query -Description "VM creation alert" -Enabled $true -EvaluationFrequency 'PT5M' -Severity 0 -WindowSize 'PT5M' -Name 'VMCreationAlert'

Activity Log Alerts for Azure Resource Events

To monitor specific Azure service events:

$condition = New-AzActivityLogAlertCondition -Field 'category' -Equal 'Administrative'
$actionGroupId = "/subscriptions/yourSubscriptionId/resourceGroups/yourResourceGroupName/providers/microsoft.insights/actionGroups/yourActionGroupName"

Set-AzActivityLogAlert -Location 'Global' -Name 'AdminActivityAlert' -ResourceGroupName 'YourResourceGroupName' -Scopes "/subscriptions/yourSubscriptionId" -Condition $condition -ActionGroupId $actionGroupId -Description "Alert on administrative activities"

Application Insights Alerts for Application Performance

Track application performance with a simple AppInsights web test

$rule = New-AzApplicationInsightsWebTestAlertRule -Name 'AppPerfAlert' -ResourceGroupName 'YourResourceGroupName' -Location 'East US' -WebTestId '/subscriptions/yourSubscriptionId/resourceGroups/yourResourceGroupName/providers/microsoft.insights/webtests/yourWebTestId' -FailedLocationCount 3 -WindowSize 'PT5M' -Frequency 'PT1M' -Criteria $criteria

Set-AzApplicationInsightsWebTestAlertRule -InputObject $rule

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 {

    $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://$$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: $_"

Azure Inventory Management with PowerShell

Listen – creating resources in Azure with PowerShell is easy – but actually knows what you have deployed is something else. Let’s dive into the steps to harness the power of PowerShell for a streamlined Azure inventory process.


Before we embark on this journey, ensure you have:

  • An Azure account with necessary access permissions.
  • PowerShell and the Azure PowerShell module ready on your machine.

Configuring PowerShell for Azure

Connecting to Azure is the first step. Open your PowerShell window and enter these commands. This should let you set your context from the Gridview.

# Connect to Azure with interactive login

# List subscriptions and select one interactively
Get-AzSubscription | Out-GridView -PassThru | Set-AzContext

Lets go ahead and start to look at your resources:

# List all resources and export to CSV
Get-AzResource | Select-Object ResourceType, Name, Location | Export-Csv -Path ./AllResources.csv -NoTypeInformation

# VM Inventory: List VMs and export their details
Get-AzVM | Select-Object Name, Location, HardwareProfile.VmSize | Export-Csv -Path ./VMInventory.csv -NoTypeInformation

# Storage Accounts: List accounts and export their details
Get-AzStorageAccount | Select-Object StorageAccountName, Location, SkuName | Export-Csv -Path ./StorageAccounts.csv -NoTypeInformation

# Network Resources: List VNets and export their details
Get-AzVirtualNetwork | Select-Object Name, Location, AddressSpace | Export-Csv -Path ./VNetInventory.csv -NoTypeInformation

In the scripts above, each command not only fetches the necessary details but also exports them to a CSV file for easy access and reporting.

Advanced Techniques

Organizing and managing your resources effectively can further be achieved by using tags.

# Organizing resources with Tags: Filter by tag and export
Get-AzResource -Tag @{ Department="Finance"} | Select-Object Name, ResourceType | Export-Csv -Path ./FinanceResources.csv -NoTypeInformation

For more insights and advanced techniques, visit the Azure PowerShell documentation. Here’s to efficient management of your Azure resources. Happy scripting!