Skip to content

Automation

πŸ€– First Steps into AI Automation: My Journey from Trial to Self-Hosted Chaos

What started as 'let me just automate some emails' somehow turned into a comprehensive exploration of every AI automation platform and deployment method known to mankind...

After months of reading about AI automation tools and watching everyone else's productivity skyrocket with clever workflows, I finally decided to stop being a spectator and dive in myself. What started as a simple "let's automate job alert emails" experiment quickly became a week-long journey through cloud trials, self-hosted deployments, OAuth authentication battles, and enough Docker containers to power a small data centre.

In this post, you'll discover:

  • Real costs of AI automation experimentation ($10-50 range)
  • Why self-hosted OAuth2 is significantly harder than cloud versions
  • Performance differences: Pi 5 vs. desktop hardware for local AI
  • When to choose local vs. cloud AI models
  • Time investment reality: ~10 hours over 1 week for this project

Here's how my first real foray into AI automation unfolded β€” spoiler alert: it involved more container migrations than I initially planned.

Hardware baseline for this project:

πŸ’» Development Environment

  • Primary machine: AMD Ryzen 7 5800X, 32GB DDR4, NVMe SSD
  • Pi 5 setup: 8GB RAM, microSD storage
  • Network: Standard home broadband (important for cloud API performance)

🎯 The Mission: Taming Job Alert Email Chaos

Let's set the scene. If you're drowning in recruitment emails like I was, spending 30+ minutes daily parsing through multiple job listings scattered across different emails, you'll understand the frustration. Each recruitment platform has its own format, some emails contain 5-10 different opportunities, and manually extracting the relevant URLs was becoming a productivity killer.

The vision: Create an automated workflow that would:

  • Scrape job-related emails from my Outlook.com inbox
  • Extract and clean the job data using AI
  • Generate a neat summary email with all the job URLs in one place
  • Send it back to me in a digestible format

Simple enough, right? Famous last words.


πŸ”„ Phase 1: The n8n Cloud Trial Adventure

My research pointed to n8n as the go-to tool for this kind of automation workflow. Being sensible, I started with their 14-day cloud trial rather than jumping straight into self-hosting complexities.

βš™οΈ Initial Setup & First Success

The n8n cloud interface is genuinely impressive β€” drag-and-drop workflow building with a proper visual editor that actually makes sense. Within a couple of hours, I had:

βœ… Connected to Outlook.com via their built-in connector
βœ… Set up email filtering to grab job-related messages
βœ… Configured basic data processing to extract text content
βœ… Integrated OpenAI API for intelligent job URL extraction

n8n jobs workflow with OpenAI API integration

πŸ€– The AI Integration Challenge

This is where things got interesting. Initially, I connected the workflow to my OpenAI API account, using GPT-4 to parse email content and extract job URLs. The AI component worked brilliantly β€” almost too well, since I managed to burn through my $10 worth of token credits in just two days of testing.

The cost reality: Those "just testing a few prompts" sessions add up fast. A single complex email with multiple job listings processed through GPT-4 was costing around $0.15-0.30 per API call. When you're iterating on prompts and testing edge cases, those costs compound quickly.

Lesson learned: Test with smaller models first, then scale up. GPT-4 is excellent but not cheap for experimental workflows.

🎯 Partial Success (The Classic IT Story)

The workflow was partially successful β€” and in true IT fashion, "partially" is doing some heavy lifting here. While the automation successfully processed emails and generated summaries, it had one glaring limitation: it only extracted one job URL per email, when most recruitment emails contain multiple opportunities.

What this actually meant: A typical recruitment email might contain 5-7 job listings with individual URLs, but my workflow would only capture the first one it encountered. This wasn't a parsing issue β€” the AI was correctly identifying all the URLs in its response, but the n8n workflow was only processing the first result from the AI output.

Why this limitation exists: The issue stemmed from how I'd configured the data processing nodes in n8n. The workflow was treating the AI response as a single data item rather than an array of multiple URLs. This is a common beginner mistake when working with structured data outputs.

This became the recurring theme of my experimentation week: everything works, just not quite how you want it to.

πŸ’‘ Enter Azure OpenAI

Rather than continue burning through OpenAI credits, I pivoted to Azure OpenAI. This turned out to be a smart move for several reasons:

  • Cost control: Better integration with my existing Azure credits
  • Familiar environment: Already comfortable with Azure resource management
  • Testing flexibility: My Visual Studio Developer subscription gives me Β£120 monthly credits

I deployed a GPT-4 Mini model in my test lab Azure tenant β€” perfect for experimentation without breaking the bank.

Azure OpenAI GPT-4 Mini deployment configuration

The Azure OpenAI integration worked seamlessly with n8n, and I successfully redirected my workflow to use the new endpoint. Finally, something that worked first time.

n8n jobs workflow with Azure OpenAI integration


🐳 Phase 2: Self-Hosting Ambitions (Container Edition #1)

With the n8n cloud trial clocking ticking down, I faced the classic build-vs-buy decision. The cloud version was excellent, but I wanted full control and the ability to experiment without subscription constraints. The monthly $20 cost wasn't prohibitive, but the learning opportunity of self-hosting was too appealing to pass up.

Enter self-hosting with Docker containers β€” specifically, targeting my Raspberry Pi 5 setup.

🏠 The OpenMediaVault Experiment

My first attempt involved deploying n8n as a self-hosted Docker container on my OpenMediaVault (OMV) setup. For those unfamiliar, OMV is a network-attached storage (NAS) solution built on Debian, perfect for home lab environments where you want proper storage management with container capabilities.

Why the Pi 5 + OMV route:

  • Always-on availability: Unlike my main PC, the Pi runs 24/7
  • Low power consumption: Perfect for continuous automation workflows
  • Storage integration: OMV provides excellent Docker volume management
  • Learning opportunity: Understanding self-hosted deployment challenges

The setup:

  • Host: Raspberry Pi 5 running OpenMediaVault
  • Backend storage: NAS device for persistent data
  • Database: PostgreSQL container for n8n's backend
  • Edition: n8n Community Edition (self-hosted)

OpenMediaVault Docker container management interface

😀 The Great OAuth Authentication Battle

This is where my self-hosting dreams met reality with a resounding thud.

I quickly discovered that replicating my cloud workflow wasn't going to be straightforward. The self-hosted community edition has functionality restrictions compared to the cloud version, but more frustratingly, I couldn't get OAuth2 authentication working properly.

Why OAuth2 is trickier with self-hosted setups:

  • Redirect URI complexity: Cloud services handle callback URLs automatically, but self-hosted instances need manually configured redirect URIs
  • App registration headaches: Azure app registrations expect specific callback patterns that don't align well with dynamic self-hosted URLs
  • Token management: Cloud versions handle OAuth token refresh automatically; self-hosted requires manual configuration
  • Security certificate requirements: Many OAuth providers now require HTTPS callbacks, adding SSL certificate management complexity

The specific challenges I hit:

  • Outlook.com authentication: Couldn't configure OAuth2 credentials using an app registration from my test lab Azure tenant
  • Exchange Online integration: Also failed to connect via app registration β€” kept getting "invalid redirect URI" errors
  • Documentation gaps: Self-hosting authentication setup felt less polished than the cloud version

After several hours over two days debugging OAuth flows and Azure app registrations, I admitted defeat on the email integration front. Sometimes retreat is the better part of valour.

🌀️ Simple Success: Weather API Workflow

Rather than abandon the entire self-hosting experiment, I pivoted to a simpler proof-of-concept. I created a basic workflow using:

  • OpenWeatherMap API for weather data
  • Gmail integration with app passwords (much simpler than OAuth2)
  • Basic data processing and email generation

This worked perfectly and proved that the self-hosted n8n environment was functional β€” the issue was specifically with the more complex authentication requirements of my original workflow.

Simple n8n weather workflow using OpenAI API


🐳 Phase 3: The WSL Migration (Container Migration #2)

While the Pi 5 setup was working fine for simple workflows, I started feeling the hardware limitations when testing more complex operations. Loading even smaller AI models was painfully slow, and memory constraints meant I couldn't experiment with anything approaching production-scale workflows.

Time for Container Migration #2.

πŸ–₯️ Moving to WSL + Docker Desktop

With the Pi 5 hitting performance limits, I decided to experiment with local AI models using Ollama (a local LLM hosting platform) and OpenWebUI (a web interface for interacting with AI models). This required more computational resources than the Pi could provide, so I deployed these tools using Docker Compose inside Ubuntu running on Windows WSL (Windows Subsystem for Linux).

This setup offered several advantages:

Why WSL over the Pi 5:

  • Better hardware resources: Access to my Windows PC's 32GB RAM and 8-core CPU vs. Pi 5's 8GB RAM limitation
  • Docker Desktop integration: Visual container management through familiar interface
  • Development flexibility: Easier to iterate and debug workflows with full IDE access
  • Performance reality: Local LLM model loading went from 1+ minutes on Pi 5 to under 30 seconds

My development machine specs:

  • CPU: AMD Ryzen 7 5800H with Radeon Graphics
  • RAM: 32GB DDR4
  • Storage: NVMe SSD for fast model loading
  • GPU: None (pure CPU inference)

Time Investment Reality:

  • n8n cloud setup: 2-3 hours (including initial workflow creation)
  • OAuth2 debugging: 3+ hours over 2 days (ongoing challenge)
  • Pi 5 container setup: 2+ hours
  • Docker Desktop container set up: 2+ hours
  • Total project time: ~10 hours over 1 week

The new stack:

  • Host: Ubuntu in WSL2 on Windows
  • Container orchestration: Docker Compose
  • Management: Docker Desktop for Windows
  • Models: Ollama for local LLM hosting
  • Interface: OpenWebUI for model interaction

Docker Desktop showing Ollama containers running

🧠 Local LLM Experimentation

This is where the project took an interesting turn. Rather than continuing to rely on cloud APIs, I started experimenting with local language models through Ollama.

Why local LLMs?

  • Cost control: No per-token charges for experimentation
  • Privacy: Sensitive data stays on local infrastructure
  • Learning opportunity: Understanding how different models perform

The Docker Compose setup made it trivial to spin up different model combinations and test their performance on my email processing use case.

⚠️ Reality Check: Local vs. Cloud Performance

Let's be honest here β€” using an LLM locally is never going to be a fully featured replacement for the likes of ChatGPT or Claude. This became apparent pretty quickly during my testing.

Performance realities:

  • Speed: Unless you're running some serious hardware, the performance will be a lot slower than the online AI counterparts
  • Model capabilities: Local models (especially smaller ones that run on consumer hardware) lack the sophisticated reasoning of GPT-4 or Claude
  • Resource constraints: My standard PC setup meant I was limited to smaller model variants
  • Response quality: Noticeably less nuanced and accurate responses compared to cloud services

Where local LLMs do shine:

  • Privacy-sensitive tasks: When you can't send data to external APIs
  • Development and testing: Iterating on prompts without burning through API credits
  • Learning and experimentation: Understanding how different model architectures behave
  • Offline scenarios: When internet connectivity is unreliable

The key insight: local LLMs are a complement to cloud services, not a replacement. Use them when privacy, cost, or learning are the primary concerns, but stick with cloud APIs when you need reliable, high-quality results.

πŸ”— Hybrid Approach: Best of Both Worlds

The final configuration became a hybrid approach:

  • OpenWebUI connected to Azure OpenAI for production-quality responses
  • Local Ollama models for development and privacy-sensitive testing
  • Docker containers exposed through Docker Desktop for easy management

This gave me the flexibility to choose the right tool for each task β€” cloud APIs when I need reliability and performance, local models when I want to experiment or maintain privacy.

OpenWebUI local interface with model selection

πŸ’° Cost Reality Check

After a week of experimentation, here's how the costs actually broke down:

Service Trial Period Monthly Cost My Usage Notes
n8n Cloud 14 days free €20/month 2 weeks testing Full OAuth2 features
OpenAI API Pay-per-use Variable $10 in 2 days Expensive for testing
Azure OpenAI Free credits Β£120/month budget ~Β£15 used Better for experimentation
Self-hosted Free Hardware + time 2 days setup OAuth2 complexity

Key insight: The "free" self-hosted option came with a significant time cost β€” debugging authentication issues for hours vs. having things work immediately in the cloud version.


πŸ“Š Current State: Lessons Learned & Next Steps

After a week of container deployments, OAuth battles, and API integrations, here's where I've landed:

βœ… What's Working Well

Technical Stack:

  • n8n self-hosted: Currently running 2 active workflows (weather alerts, basic data processing)
  • Azure OpenAI integration: Reliable and cost-effective for AI processing β€” saving ~Β£25/month vs. direct OpenAI API
  • Docker containerisation: Easy deployment and management across different environments
  • WSL environment: 10x performance improvement over Pi 5 for local AI model loading

Process Improvements:

  • Iterative approach: Start simple, add complexity gradually β€” this saved significant debugging time
  • Hybrid cloud/local strategy: Use the right tool for each requirement rather than forcing one solution
  • Container flexibility: Easy to migrate and scale across different hosts when hardware constraints appear

Daily productivity impact: While the original job email automation isn't fully solved, the weather automation saves ~10 minutes daily, and the learning has already paid dividends in other automation projects.

⚠️ Ongoing Challenges (The Work-in-Progress List)

Authentication Issues:

  • OAuth2 integration with Outlook.com/Exchange Online still unresolved
  • Need to explore alternative authentication methods or different email providers
  • May require diving deeper into Azure app registration configurations

Workflow Limitations:

  • Original job email processing goal partially achieved but needs refinement
  • Multiple job URL extraction per email still needs work
  • Error handling and retry logic need improvement

Infrastructure Decisions:

  • Balancing local vs. cloud resources for different use cases
  • Determining optimal Docker deployment strategy for production workflows
  • Managing costs across multiple AI service providers

Decision-making process during failures: When something doesn't work, I typically: (1) Troubleshoot the exact error using ChatGPT or Anthropic Claude, (2) Search for similar issues in community forums, (3) Try a simpler alternative approach, (4) If still stuck after 2-3 hours, pivot to a different method rather than continuing to debug indefinitely.

πŸš€ Next Steps & Future Experiments

Short-term goals (next 2-4 weeks):

  1. Resolve OAuth2 authentication for proper email integration
  2. Improve job URL extraction accuracy β€” tackle the multiple URLs per email challenge
  3. Add error handling and logging to existing workflows
  4. Explore alternative email providers if Outlook.com integration remains problematic

Medium-term exploration (next 2-3 months):

  1. Local LLM performance tuning for specific use cases
  2. Workflow templates for common automation patterns
  3. Integration with other productivity tools (calendar, task management)
  4. Monitoring and alerting for automated workflows

πŸ› οΈ Quick Wins for Beginners

If you're just starting your AI automation journey, here are the lessons learned that could save you time:

🎯 Start Simple First

  • Begin with n8n cloud trial to understand the platform without authentication headaches
  • Use simple APIs (weather, RSS feeds) before tackling complex ones (email OAuth2)
  • Test with smaller AI models before jumping to GPT-4

πŸ’‘ Budget for Experimentation

  • Set aside $20-50 for API testing β€” it goes faster than you think
  • Azure OpenAI credits can be more cost-effective than direct OpenAI API for learning
  • Factor in time costs when choosing self-hosted vs. cloud solutions

πŸ”§ Have Fallback Options Ready

  • Plan alternative authentication methods (app passwords vs. OAuth2)
  • Keep both cloud and local AI options available
  • Document what works and what doesn't for future reference

πŸ”§ Technical Resources & Documentation

For anyone inspired to start their own AI automation journey, here are the key resources that proved invaluable:

πŸ› οΈ Core Tools & Platforms

  • n8n β€” Visual workflow automation platform
  • Docker β€” Containerisation platform
  • Docker Compose β€” Multi-container orchestration tool
  • OpenMediaVault β€” NAS/storage management solution

πŸ€– AI & LLM Resources

πŸ“š Setup Guides & Documentation

πŸ”§ Troubleshooting Common Issues

Based on my week of trial and error, here are the most common problems you'll likely encounter:

πŸ” OAuth2 Authentication Failures

Symptoms: "Invalid redirect URI" or "Authentication failed" errors when connecting to email services.

Likely causes:

  • Redirect URI mismatch between app registration and n8n configuration
  • Self-hosted instance not using HTTPS for callbacks
  • App registration missing required API permissions

Solutions to try:

  • Use app passwords instead of OAuth2 where possible (Gmail, Outlook.com) β€” Note: App passwords are simpler username/password credentials that bypass OAuth2 complexity but offer less security
  • Ensure your n8n instance is accessible via HTTPS with valid SSL certificate
  • Double-check app registration redirect URIs match exactly (including trailing slashes)
  • Start with cloud trial to verify workflow logic before self-hosting

🐳 Container Performance Issues

Symptoms: Slow model loading, container crashes, high memory usage.

Likely causes:

  • Insufficient RAM allocation to Docker
  • CPU-intensive models running on inadequate hardware
  • Competing containers for limited resources

Solutions to try:

  • Increase Docker memory limits in Docker Desktop settings
  • Use smaller model variants (7B instead of 13B+ parameters)
  • Monitor resource usage with docker stats command
  • Consider migrating from Pi to x86 hardware for better performance

πŸ’Έ API Rate Limiting and Costs

Symptoms: API calls failing, unexpected high costs, token limits exceeded.

Likely causes:

  • Testing with expensive models (GPT-4) instead of cheaper alternatives
  • No rate limiting in workflow configurations
  • Inefficient prompt design causing high token usage

Solutions to try:

  • Start testing with GPT-3.5-turbo or GPT-4-mini models
  • Implement workflow rate limiting and retry logic
  • Optimize prompts to reduce token consumption
  • Set API spending alerts in provider dashboards

πŸ’» Resource Requirements Summary

Minimum Requirements for Recreation:

  • Cloud approach: n8n trial account + $20-50 API experimentation budget
  • Self-hosted approach: 8GB+ RAM, Docker knowledge, 2-3 days setup time
  • Local AI experimentation: 16GB+ RAM recommended, considerable patience, NVMe storage preferred
  • Network: Stable broadband connection for cloud API performance

πŸ’­ Final Thoughts: The Joy of Controlled Chaos

What started as a simple email automation project became a comprehensive exploration of modern AI automation tools. While I didn't achieve my original goal completely (yet), the journey provided invaluable hands-on experience with:

  • Container orchestration across different environments
  • AI service integration patterns and best practices
  • Authentication complexity in self-hosted vs. cloud environments
  • Hybrid deployment strategies for flexibility and cost control

The beauty of this approach is that each "failed" experiment taught me something valuable about the tools and processes involved. The OAuth2 authentication issues, while frustrating, highlighted the importance of proper authentication design. The container migrations demonstrated the flexibility of modern deployment approaches.

Most importantly: I now have a functional foundation for AI automation experiments, with both cloud and local capabilities at my disposal.

Is it overengineered for a simple email processing task? Absolutely. Was it worth the learning experience? Without question.

Have you tackled similar AI automation projects? I'd particularly love to hear from anyone who's solved the OAuth2 self-hosting puzzle or found creative workarounds for email processing limitations. Drop me a line if you've found better approaches to any of these challenges.


πŸ“Έ Image Requirements Summary

For anyone recreating this setup, here are the key screenshots included in this post:

  1. n8n-jobs-workflow-openai.png β€” Original workflow using direct OpenAI API (the expensive version that burned through $10 in 2 days)
  2. azure-openai-deployment.png β€” Azure OpenAI Studio showing GPT-4 Mini deployment configuration
  3. n8n-jobs-workflow-azure.png β€” Improved workflow using Azure OpenAI integration (the cost-effective version)
  4. omv-docker-n8n-containers.png β€” OpenMediaVault interface showing Docker container management on Pi 5
  5. n8n-weather-workflow.png β€” Simple weather API to Gmail workflow demonstrating successful self-hosted setup
  6. docker-desktop-ollama.png β€” Docker Desktop showing Ollama and OpenWebUI containers running on WSL
  7. openwebui-local.png β€” OpenWebUI interface showing both Azure OpenAI and local model selection options

Each image demonstrates the practical implementation rather than theoretical concepts, helping readers visualize the actual tools and interfaces involved in the automation journey.

Share on Share on

πŸ”„ Bringing Patch Management In-House: Migrating from MSP to Azure Update Manager

It's all fun and games until the MSP contract expires and you realise 90 VMs still need their patching schedules sorted…

With our MSP contract winding down, the time had come to bring VM patching back in house. Our third-party provider had been handling it with their own tooling, which would no longer be used when the service contract expired.

Enter Azure Update Manager β€” the modern, agentless way to manage patching schedules across your Azure VMs. Add a bit of PowerShell, sprinkle in some Azure Policy, and you've got yourself a scalable, policy-driven solution that's more visible, auditable, and way more maintainable.

Here's how I made the switch β€” and managed to avoid a patching panic.


βš™οΈ Prerequisites & Permissions

Let's get the plumbing sorted before diving in.

You'll need:

  • The right PowerShell modules:
Install-Module Az -Scope CurrentUser -Force
Import-Module Az.Maintenance, Az.Resources, Az.Compute
  • An account with Contributor permissions (or higher)
  • Registered providers to avoid mysterious error messages:
Register-AzResourceProvider -ProviderNamespace Microsoft.Maintenance
Register-AzResourceProvider -ProviderNamespace Microsoft.GuestConfiguration

Why Resource Providers? Azure Update Manager needs these registered to create the necessary API endpoints and resource types in your subscription. Without them, you'll get cryptic "resource type not found" errors.

Official documentation on Azure Update Manager prerequisites


πŸ•΅οΈ Step 1 – Audit the Current Setup

First order of business: collect the patching summary data from the MSP β€” which, helpfully, came in the form of multiple weekly CSV exports.

I used GenAI to wrangle the mess into a structured format. The result was a clear categorisation of VMs based on the day and time they were typically patched β€” a solid foundation to work from.


🧱 Step 2 – Create Seven New Maintenance Configurations

This is the foundation of Update Manager β€” define your recurring patch windows.

Click to expand: Create Maintenance Configurations (Sample Script)
# Azure Update Manager - Create Weekly Maintenance Configurations
# Pure PowerShell syntax

# Define parameters
$resourceGroupName = "rg-maintenance-uksouth-001"
$location = "uksouth"
$timezone = "GMT Standard Time"
$startDateTime = "2024-06-01 21:00"
$duration = "03:00"  # 3 hours - meets minimum requirement

# Day mapping for config naming (3-letter lowercase)
$dayMap = @{
    "Monday"    = "mon"
    "Tuesday"   = "tue" 
    "Wednesday" = "wed"
    "Thursday"  = "thu"
    "Friday"    = "fri"
    "Saturday"  = "sat"
    "Sunday"    = "sun"
}

# Create maintenance configurations for each day
foreach ($day in $dayMap.Keys) {
    $shortDay = $dayMap[$day]
    $configName = "contoso-maintenance-config-vms-$shortDay"

    Write-Host "Creating: $configName for $day..." -ForegroundColor Yellow

    try {
        $result = New-AzMaintenanceConfiguration `
            -ResourceGroupName $resourceGroupName `
            -Name $configName `
            -MaintenanceScope "InGuestPatch" `
            -Location $location `
            -StartDateTime $startDateTime `
            -Timezone $timezone `
            -Duration $duration `
            -RecurEvery "Week $day" `
            -InstallPatchRebootSetting "IfRequired" `
            -ExtensionProperty @{"InGuestPatchMode" = "User"} `
            -WindowParameterClassificationToInclude @("Critical", "Security") `
            -LinuxParameterClassificationToInclude @("Critical", "Security") `
            -Tag @{
                "Application"  = "Azure Update Manager"
                "Owner"        = "Contoso"
                "PatchWindow"  = $shortDay
            } `
            -ErrorAction Stop

        Write-Host "βœ“ SUCCESS: $configName" -ForegroundColor Green

        # Quick validation
        $createdConfig = Get-AzMaintenanceConfiguration -ResourceGroupName $resourceGroupName -Name $configName
        Write-Host "  Validated: $($createdConfig.RecurEvery) schedule confirmed" -ForegroundColor Gray

    } catch {
        Write-Host "βœ— FAILED: $configName - $($_.Exception.Message)" -ForegroundColor Red
        continue
    }
}

⚠️ Don't forget: duration format is ISO 8601, not "2 hours" β€” and start time has to match the day it's tied to.

Learn more about New-AzMaintenanceConfiguration


πŸ› οΈ Step 3 – Tweak the Maintenance Configs

Some patch windows felt too tight β€” and, just as importantly, I needed to avoid overlaps with existing backup jobs. Rather than let a large CU fail halfway through or run headlong into an Azure Backup job, I extended the duration on select configs and staggered them across the week:

$config = Get-AzMaintenanceConfiguration -ResourceGroupName "rg-maintenance-uksouth-001" -Name "contoso-maintenance-config-vms-sun"
$config.Duration = "04:00"
Update-AzMaintenanceConfiguration -ResourceGroupName "rg-maintenance-uksouth-001" -Name "contoso-maintenance-config-vms-sun" -Configuration $config

# Verify the change
$updatedConfig = Get-AzMaintenanceConfiguration -ResourceGroupName "rg-maintenance-uksouth-001" -Name "contoso-maintenance-config-vms-sun"
Write-Host "Sunday window now: $($updatedConfig.Duration) duration" -ForegroundColor Green

Learn more about Update-AzMaintenanceConfiguration


πŸ€– Step 4 – Use AI to Group VMs by Patch Activity

Armed with CSV exports of the latest patching summaries, I got AI to do the grunt work and make sense of the contents.

What I did:

  1. Exported MSP data: Weekly CSV reports showing patch installation timestamps for each VM
  2. Used Gen AI with various iterative prompts, starting the conversation with this:

    "Attached is an export summary of the current patching activity from our incumbent MSP who currently look after the patching of the VM's in Azure I need you to review timestamps and work out which maintenance window each vm is currently in, and then match that to the appropriate maintenance config that we have just created. If there are mis matches in new and current schedule then we may need to tweak the settings of the new configs"

  3. AI analysis revealed:

  4. 60% of VMs were patching on one weekday evening
  5. Several critical systems patching simultaneously
  6. No consideration for application dependencies

  7. AI recommendation: Spread VMs across weekdays based on:

  8. Criticality: Domain controllers on different days
  9. Function: Similar servers on different days (avoid single points of failure)
  10. Dependencies: Database servers before application servers

The result: A logical rebalancing that avoided "all our eggs in Sunday 1AM" basket and considered business impact.

Why this matters: The current patching schedule was not optimized for business continuity. AI helped identify risks we hadn't considered.


πŸ” Step 5 – Discover All VMs and Identify Gaps

Before diving into bulk tagging, I needed to understand what we were working with across all subscriptions.

First, let's see what VMs we have:

Click to expand: Discover Untagged VMs (Sample Script)
# Discover Untagged VMs Script for Azure Update Manager
# This script identifies VMs that are missing Azure Update Manager tags

$scriptStart = Get-Date

Write-Host "=== Azure Update Manager - Discover Untagged VMs ===" -ForegroundColor Cyan
Write-Host "Scanning all accessible subscriptions for VMs missing maintenance tags..." -ForegroundColor White
Write-Host ""

# Function to check if VM has Azure Update Manager tags
function Test-VMHasMaintenanceTags {
    param($VM)

    # Check for the three required tags
    $hasOwnerTag = $VM.Tags -and $VM.Tags.ContainsKey("Owner") -and $VM.Tags["Owner"] -eq "Contoso"
    $hasUpdatesTag = $VM.Tags -and $VM.Tags.ContainsKey("Updates") -and $VM.Tags["Updates"] -eq "Azure Update Manager"
    $hasPatchWindowTag = $VM.Tags -and $VM.Tags.ContainsKey("PatchWindow")

    return $hasOwnerTag -and $hasUpdatesTag -and $hasPatchWindowTag
}

# Function to get VM details for reporting
function Get-VMDetails {
    param($VM, $SubscriptionName)

    return [PSCustomObject]@{
        Name = $VM.Name
        ResourceGroup = $VM.ResourceGroupName
        Location = $VM.Location
        Subscription = $SubscriptionName
        SubscriptionId = $VM.SubscriptionId
        PowerState = $VM.PowerState
        OsType = $VM.StorageProfile.OsDisk.OsType
        VmSize = $VM.HardwareProfile.VmSize
        Tags = if ($VM.Tags) { ($VM.Tags.Keys | ForEach-Object { "$_=$($VM.Tags[$_])" }) -join "; " } else { "No tags" }
    }
}

# Initialize collections
$taggedVMs = @()
$untaggedVMs = @()
$allVMs = @()
$subscriptionSummary = @{}

Write-Host "=== DISCOVERING VMs ACROSS ALL SUBSCRIPTIONS ===" -ForegroundColor Cyan

# Get all accessible subscriptions
$subscriptions = Get-AzSubscription | Where-Object { $_.State -eq "Enabled" }
Write-Host "Found $($subscriptions.Count) accessible subscriptions" -ForegroundColor White

foreach ($subscription in $subscriptions) {
    try {
        Write-Host "`nScanning subscription: $($subscription.Name) ($($subscription.Id))" -ForegroundColor Magenta
        $null = Set-AzContext -SubscriptionId $subscription.Id -ErrorAction Stop

        # Get all VMs in this subscription
        Write-Host "  Retrieving VMs..." -ForegroundColor Gray
        $vms = Get-AzVM -Status -ErrorAction Continue

        $subTagged = 0
        $subUntagged = 0
        $subTotal = $vms.Count

        Write-Host "  Found $subTotal VMs in this subscription" -ForegroundColor White

        foreach ($vm in $vms) {
            $vmDetails = Get-VMDetails -VM $vm -SubscriptionName $subscription.Name
            $allVMs += $vmDetails

            if (Test-VMHasMaintenanceTags -VM $vm) {
                $taggedVMs += $vmDetails
                $subTagged++
                Write-Host "    βœ“ Tagged: $($vm.Name)" -ForegroundColor Green
            } else {
                $untaggedVMs += $vmDetails
                $subUntagged++
                Write-Host "    ⚠️ Untagged: $($vm.Name)" -ForegroundColor Yellow
            }
        }

        # Store subscription summary
        $subscriptionSummary[$subscription.Name] = @{
            Total = $subTotal
            Tagged = $subTagged
            Untagged = $subUntagged
            SubscriptionId = $subscription.Id
        }

        Write-Host "  Subscription Summary - Total: $subTotal | Tagged: $subTagged | Untagged: $subUntagged" -ForegroundColor Gray

    }
    catch {
        Write-Host "  βœ— Error scanning subscription $($subscription.Name): $($_.Exception.Message)" -ForegroundColor Red
        $subscriptionSummary[$subscription.Name] = @{
            Total = 0
            Tagged = 0
            Untagged = 0
            Error = $_.Exception.Message
        }
    }
}

Write-Host ""
Write-Host "=== OVERALL DISCOVERY SUMMARY ===" -ForegroundColor Cyan
Write-Host "Total VMs found: $($allVMs.Count)" -ForegroundColor White
Write-Host "VMs with maintenance tags: $($taggedVMs.Count)" -ForegroundColor Green
Write-Host "VMs missing maintenance tags: $($untaggedVMs.Count)" -ForegroundColor Red

if ($untaggedVMs.Count -eq 0) {
    Write-Host "οΏ½ ALL VMs ARE ALREADY TAGGED! οΏ½" -ForegroundColor Green
    Write-Host "No further action required." -ForegroundColor White
    exit 0
}

Write-Host ""
Write-Host "=== SUBSCRIPTION BREAKDOWN ===" -ForegroundColor Cyan
$subscriptionSummary.GetEnumerator() | Sort-Object Name | ForEach-Object {
    $sub = $_.Value
    if ($sub.Error) {
        Write-Host "$($_.Key): ERROR - $($sub.Error)" -ForegroundColor Red
    } else {
        $percentage = if ($sub.Total -gt 0) { [math]::Round(($sub.Tagged / $sub.Total) * 100, 1) } else { 0 }
        Write-Host "$($_.Key): $($sub.Tagged)/$($sub.Total) tagged ($percentage%)" -ForegroundColor White
    }
}

Write-Host ""
Write-Host "=== UNTAGGED VMs DETAILED LIST ===" -ForegroundColor Red
Write-Host "The following $($untaggedVMs.Count) VMs are missing Azure Update Manager maintenance tags:" -ForegroundColor White

# Group untagged VMs by subscription for easier reading
$untaggedBySubscription = $untaggedVMs | Group-Object Subscription

foreach ($group in $untaggedBySubscription | Sort-Object Name) {
    Write-Host "`nοΏ½ Subscription: $($group.Name) ($($group.Count) untagged VMs)" -ForegroundColor Magenta

    $group.Group | Sort-Object Name | ForEach-Object {
        Write-Host "  β€’ $($_.Name)" -ForegroundColor Yellow
        Write-Host "    Resource Group: $($_.ResourceGroup)" -ForegroundColor Gray
        Write-Host "    Location: $($_.Location)" -ForegroundColor Gray
        Write-Host "    OS Type: $($_.OsType)" -ForegroundColor Gray
        Write-Host "    VM Size: $($_.VmSize)" -ForegroundColor Gray
        Write-Host "    Power State: $($_.PowerState)" -ForegroundColor Gray
        if ($_.Tags -ne "No tags") {
            Write-Host "    Existing Tags: $($_.Tags)" -ForegroundColor DarkGray
        }
        Write-Host ""
    }
}

Write-Host "=== ANALYSIS BY VM CHARACTERISTICS ===" -ForegroundColor Cyan

# Analyze by OS Type
$untaggedByOS = $untaggedVMs | Group-Object OsType
Write-Host "`nοΏ½ Untagged VMs by OS Type:" -ForegroundColor White
$untaggedByOS | Sort-Object Name | ForEach-Object {
    Write-Host "  $($_.Name): $($_.Count) VMs" -ForegroundColor White
}

# Analyze by Location
$untaggedByLocation = $untaggedVMs | Group-Object Location
Write-Host "`nοΏ½ Untagged VMs by Location:" -ForegroundColor White
$untaggedByLocation | Sort-Object Count -Descending | ForEach-Object {
    Write-Host "  $($_.Name): $($_.Count) VMs" -ForegroundColor White
}

# Analyze by VM Size (to understand workload types)
$untaggedBySize = $untaggedVMs | Group-Object VmSize
Write-Host "`nοΏ½ Untagged VMs by Size:" -ForegroundColor White
$untaggedBySize | Sort-Object Count -Descending | Select-Object -First 10 | ForEach-Object {
    Write-Host "  $($_.Name): $($_.Count) VMs" -ForegroundColor White
}

# Analyze by Resource Group (might indicate application/workload groupings)
$untaggedByRG = $untaggedVMs | Group-Object ResourceGroup
Write-Host "`nοΏ½ Untagged VMs by Resource Group (Top 10):" -ForegroundColor White
$untaggedByRG | Sort-Object Count -Descending | Select-Object -First 10 | ForEach-Object {
    Write-Host "  $($_.Name): $($_.Count) VMs" -ForegroundColor White
}

Write-Host ""
Write-Host "=== POWER STATE ANALYSIS ===" -ForegroundColor Cyan
$powerStates = $untaggedVMs | Group-Object PowerState
$powerStates | Sort-Object Count -Descending | ForEach-Object {
    Write-Host "$($_.Name): $($_.Count) VMs" -ForegroundColor White
}

Write-Host ""
Write-Host "=== EXPORT OPTIONS ===" -ForegroundColor Cyan
Write-Host "You can export this data for further analysis:" -ForegroundColor White

# Export to CSV option
$timestamp = Get-Date -Format "yyyyMMdd-HHmm"
$csvPath = "D:\UntaggedVMs-$timestamp.csv"

try {
    $untaggedVMs | Export-Csv -Path $csvPath -NoTypeInformation
    Write-Host "βœ“ Exported untagged VMs to: $csvPath" -ForegroundColor Green
} catch {
    Write-Host "βœ— Failed to export CSV: $($_.Exception.Message)" -ForegroundColor Red
}

# Show simple list for easy copying
Write-Host ""
Write-Host "=== SIMPLE VM NAME LIST (for copy/paste) ===" -ForegroundColor Cyan
Write-Host "VM Names:" -ForegroundColor White
$untaggedVMs | Sort-Object Name | ForEach-Object { Write-Host "  $($_.Name)" -ForegroundColor Yellow }

Write-Host ""
Write-Host "=== NEXT STEPS RECOMMENDATIONS ===" -ForegroundColor Cyan
Write-Host "1. Review the untagged VMs list above" -ForegroundColor White
Write-Host "2. Investigate why these VMs were not in the original patching schedule" -ForegroundColor White
Write-Host "3. Determine appropriate maintenance windows for these VMs" -ForegroundColor White
Write-Host "4. Consider grouping by:" -ForegroundColor White
Write-Host "   β€’ Application/workload (Resource Group analysis)" -ForegroundColor Gray
Write-Host "   β€’ Environment (naming patterns, tags)" -ForegroundColor Gray
Write-Host "   β€’ Business criticality" -ForegroundColor Gray
Write-Host "   β€’ Maintenance window preferences" -ForegroundColor Gray
Write-Host "5. Run the tagging script to assign maintenance windows" -ForegroundColor White

Write-Host ""
Write-Host "=== AZURE RESOURCE GRAPH QUERY ===" -ForegroundColor Cyan
Write-Host "Use this query in Azure Resource Graph Explorer to verify results:" -ForegroundColor White
Write-Host ""
Write-Host @"
Resources
| where type == "microsoft.compute/virtualmachines"
| where tags.PatchWindow == "" or isempty(tags.PatchWindow) or isnull(tags.PatchWindow)
| project name, resourceGroup, subscriptionId, location, 
          osType = properties.storageProfile.osDisk.osType,
          vmSize = properties.hardwareProfile.vmSize,
          powerState = properties.extended.instanceView.powerState.displayStatus,
          tags
| sort by name asc
"@ -ForegroundColor Gray

Write-Host ""
Write-Host "Script completed at $(Get-Date)" -ForegroundColor Cyan
Write-Host "Total runtime: $((Get-Date) - $scriptStart)" -ForegroundColor Gray

Discovery results:

  • 35 VMs from the original MSP schedule (our planned list)
  • 12 additional VMs not in the MSP schedule (the "stragglers")
  • Total: 90 VMs needing Update Manager tags

Key insight: The MSP wasn't managing everything. Several dev/test VMs and a few production systems were missing from their schedule.


✍️ Step 6 – Bulk Tag All VMs with Patch Windows

Now for the main event: tagging all VMs with their maintenance windows. This includes both our planned VMs and the newly discovered ones.

🎯 Main VM Tagging (Planned Schedule)

Each tag serves a specific purpose:

  • PatchWindow β€” The key tag used by dynamic scopes to assign VMs to maintenance configurations
  • Owner β€” For accountability and filtering
  • Updates β€” Identifies VMs managed by Azure Update Manager
Click to expand: Multi-Subscription Azure Update Manager VM Tagging (Sample Script)
# Multi-Subscription Azure Update Manager VM Tagging Script
# This script discovers VMs across multiple subscriptions and tags them appropriately

Write-Host "=== Multi-Subscription Azure Update Manager - VM Tagging Script ===" -ForegroundColor Cyan

# Function to safely tag a VM
function Set-VMMaintenanceTags {
    param(
        [string]$VMName,
        [string]$ResourceGroupName,
        [string]$SubscriptionId,
        [hashtable]$Tags,
        [string]$MaintenanceWindow
    )

    try {
        # Set context to the VM's subscription
        $null = Set-AzContext -SubscriptionId $SubscriptionId -ErrorAction Stop

        Write-Host "  Processing: $VMName..." -ForegroundColor Yellow

        # Get the VM and update tags
        $vm = Get-AzVM -ResourceGroupName $ResourceGroupName -Name $VMName -ErrorAction Stop

        if ($vm.Tags) {
            $Tags.Keys | ForEach-Object { $vm.Tags[$_] = $Tags[$_] }
        } else {
            $vm.Tags = $Tags
        }

        $null = Update-AzVM -VM $vm -ResourceGroupName $ResourceGroupName -Tag $vm.Tags -ErrorAction Stop
        Write-Host "  βœ“ Successfully tagged $VMName for $MaintenanceWindow maintenance" -ForegroundColor Green

        return $true
    }
    catch {
        Write-Host "  βœ— Failed to tag $VMName`: $($_.Exception.Message)" -ForegroundColor Red
        return $false
    }
}

# Define all target VMs organized by maintenance window
$maintenanceGroups = @{
    "Monday" = @{
        "VMs" = @("WEB-PROD-01", "DB-PROD-01", "APP-PROD-01", "FILE-PROD-01", "DC-PROD-01")
        "Tags" = @{
            "Owner" = "Contoso"
            "Updates" = "Azure Update Manager"
            "PatchWindow" = "mon"
        }
    }
    "Tuesday" = @{
        "VMs" = @("WEB-PROD-02", "DB-PROD-02", "APP-PROD-02", "FILE-PROD-02", "DC-PROD-02")
        "Tags" = @{
            "Owner" = "Contoso"
            "Updates" = "Azure Update Manager"
            "PatchWindow" = "tue"
        }
    }
    "Wednesday" = @{
        "VMs" = @("WEB-PROD-03", "DB-PROD-03", "APP-PROD-03", "FILE-PROD-03", "DC-PROD-03")
        "Tags" = @{
            "Owner" = "Contoso"
            "Updates" = "Azure Update Manager"
            "PatchWindow" = "wed"
        }
    }
    "Thursday" = @{
        "VMs" = @("WEB-PROD-04", "DB-PROD-04", "APP-PROD-04", "FILE-PROD-04", "PRINT-PROD-01")
        "Tags" = @{
            "Owner" = "Contoso"
            "Updates" = "Azure Update Manager"
            "PatchWindow" = "thu"
        }
    }
    "Friday" = @{
        "VMs" = @("WEB-PROD-05", "DB-PROD-05", "APP-PROD-05", "FILE-PROD-05", "MONITOR-PROD-01")
        "Tags" = @{
            "Owner" = "Contoso"
            "Updates" = "Azure Update Manager"
            "PatchWindow" = "fri"
        }
    }
    "Saturday" = @{
        "VMs" = @("WEB-DEV-01", "DB-DEV-01", "APP-DEV-01", "TEST-SERVER-01", "SANDBOX-01")
        "Tags" = @{
            "Owner" = "Contoso"
            "Updates" = "Azure Update Manager"
            "PatchWindow" = "sat-09"
        }
    }
    "Sunday" = @{
        "VMs" = @("WEB-UAT-01", "DB-UAT-01", "APP-UAT-01", "BACKUP-PROD-01", "MGMT-PROD-01")
        "Tags" = @{
            "Owner" = "Contoso"
            "Updates" = "Azure Update Manager"
            "PatchWindow" = "sun"
        }
    }
}

# Function to discover VMs across all subscriptions
function Find-VMsAcrossSubscriptions {
    param([array]$TargetVMNames)

    $subscriptions = Get-AzSubscription | Where-Object { $_.State -eq "Enabled" }
    $vmInventory = @{}

    foreach ($subscription in $subscriptions) {
        try {
            $null = Set-AzContext -SubscriptionId $subscription.Id -ErrorAction Stop
            $vms = Get-AzVM -ErrorAction Continue

            foreach ($vm in $vms) {
                if ($vm.Name -in $TargetVMNames) {
                    $vmInventory[$vm.Name] = @{
                        Name = $vm.Name
                        ResourceGroupName = $vm.ResourceGroupName
                        SubscriptionId = $subscription.Id
                        SubscriptionName = $subscription.Name
                        Location = $vm.Location
                    }
                }
            }
        }
        catch {
            Write-Host "Error scanning subscription $($subscription.Name): $($_.Exception.Message)" -ForegroundColor Red
        }
    }

    return $vmInventory
}

# Get all unique VM names and discover their locations
$allTargetVMs = @()
$maintenanceGroups.Values | ForEach-Object { $allTargetVMs += $_.VMs }
$allTargetVMs = $allTargetVMs | Sort-Object -Unique

Write-Host "Discovering locations for $($allTargetVMs.Count) target VMs..." -ForegroundColor White
$vmInventory = Find-VMsAcrossSubscriptions -TargetVMNames $allTargetVMs

# Process each maintenance window
$totalSuccess = 0
$totalFailed = 0

foreach ($windowName in $maintenanceGroups.Keys) {
    $group = $maintenanceGroups[$windowName]
    Write-Host "`n=== $windowName MAINTENANCE WINDOW ===" -ForegroundColor Magenta

    foreach ($vmName in $group.VMs) {
        if ($vmInventory.ContainsKey($vmName)) {
            $vmInfo = $vmInventory[$vmName]
            $result = Set-VMMaintenanceTags -VMName $vmInfo.Name -ResourceGroupName $vmInfo.ResourceGroupName -SubscriptionId $vmInfo.SubscriptionId -Tags $group.Tags -MaintenanceWindow $windowName
            if ($result) { $totalSuccess++ } else { $totalFailed++ }
        } else {
            Write-Host "  ⚠️ VM not found: $vmName" -ForegroundColor Yellow
            $totalFailed++
        }
    }
}

Write-Host "`n=== TAGGING SUMMARY ===" -ForegroundColor Cyan
Write-Host "Successfully tagged: $totalSuccess VMs" -ForegroundColor Green
Write-Host "Failed to tag: $totalFailed VMs" -ForegroundColor Red

🧹 Handle the Stragglers

For the 12 VMs not in the original MSP schedule, I used intelligent assignment based on their function:

Click to expand: Tagging Script for Remaining Untagged VMs (Sample Script)
# Intelligent VM Tagging Script for Remaining Untagged VMs
# This script analyzes and tags the remaining VMs based on workload patterns and load balancing

$scriptStart = Get-Date

Write-Host "=== Intelligent VM Tagging for Remaining VMs ===" -ForegroundColor Cyan
Write-Host "Analyzing and tagging 26 untagged VMs with optimal maintenance window distribution..." -ForegroundColor White
Write-Host ""

# Function to safely tag a VM across subscriptions
function Set-VMMaintenanceTags {
    param(
        [string]$VMName,
        [string]$ResourceGroupName,
        [string]$SubscriptionId,
        [hashtable]$Tags,
        [string]$MaintenanceWindow
    )

    try {
        # Set context to the VM's subscription
        $currentContext = Get-AzContext
        if ($currentContext.Subscription.Id -ne $SubscriptionId) {
            $null = Set-AzContext -SubscriptionId $SubscriptionId -ErrorAction Stop
        }

        Write-Host "  Processing: $VMName..." -ForegroundColor Yellow

        # Get the VM
        $vm = Get-AzVM -ResourceGroupName $ResourceGroupName -Name $VMName -ErrorAction Stop

        # Add maintenance tags to existing tags (preserve existing tags)
        if ($vm.Tags) {
            $Tags.Keys | ForEach-Object {
                $vm.Tags[$_] = $Tags[$_]
            }
        } else {
            $vm.Tags = $Tags
        }

        # Update the VM tags
        $null = Update-AzVM -VM $vm -ResourceGroupName $ResourceGroupName -Tag $vm.Tags -ErrorAction Stop
        Write-Host "  βœ“ Successfully tagged $VMName for $MaintenanceWindow maintenance" -ForegroundColor Green

        return $true
    }
    catch {
        Write-Host "  βœ— Failed to tag $VMName`: $($_.Exception.Message)" -ForegroundColor Red
        return $false
    }
}

# Define current maintenance window loads (after existing 59 VMs)
$currentLoad = @{
    "Monday" = 7
    "Tuesday" = 7 
    "Wednesday" = 10
    "Thursday" = 6
    "Friday" = 6
    "Saturday" = 17  # Dev/Test at 09:00
    "Sunday" = 6
}

Write-Host "=== CURRENT MAINTENANCE WINDOW LOAD ===" -ForegroundColor Cyan
$currentLoad.GetEnumerator() | Sort-Object Name | ForEach-Object {
    Write-Host "$($_.Key): $($_.Value) VMs" -ForegroundColor White
}

# Initialize counters for new assignments
$newAssignments = @{
    "Monday" = 0
    "Tuesday" = 0
    "Wednesday" = 0
    "Thursday" = 0
    "Friday" = 0
    "Saturday" = 0  # Will use sat-09 for dev/test
    "Sunday" = 0
}

Write-Host ""
Write-Host "=== INTELLIGENT VM GROUPING AND ASSIGNMENT ===" -ForegroundColor Cyan

# Define VM groups with intelligent maintenance window assignments
$vmGroups = @{

    # CRITICAL PRODUCTION SYSTEMS - Spread across different days
    "Critical Infrastructure" = @{
        "VMs" = @(
            @{ Name = "DC-PROD-01"; RG = "rg-infrastructure"; Sub = "Production"; Window = "Sunday"; Reason = "Domain Controller - critical infrastructure" },
            @{ Name = "DC-PROD-02"; RG = "rg-infrastructure"; Sub = "Production"; Window = "Monday"; Reason = "Domain Controller - spread from other DCs" },
            @{ Name = "BACKUP-PROD-01"; RG = "rg-backup"; Sub = "Production"; Window = "Tuesday"; Reason = "Backup Server - spread across week" }
        )
    }

    # PRODUCTION BUSINESS APPLICATIONS - Spread for business continuity
    "Production Applications" = @{
        "VMs" = @(
            @{ Name = "WEB-PROD-01"; RG = "rg-web-production"; Sub = "Production"; Window = "Monday"; Reason = "Web Server - Monday for week start" },
            @{ Name = "DB-PROD-01"; RG = "rg-database-production"; Sub = "Production"; Window = "Tuesday"; Reason = "Database Server - Tuesday" },
            @{ Name = "APP-PROD-01"; RG = "rg-app-production"; Sub = "Production"; Window = "Wednesday"; Reason = "Application Server - mid-week" }
        )
    }

    # DEV/TEST SYSTEMS - Saturday morning maintenance (like existing dev/test)
    "Development Systems" = @{
        "VMs" = @(
            @{ Name = "WEB-DEV-01"; RG = "rg-web-development"; Sub = "Development"; Window = "Saturday"; Reason = "Web Dev - join existing dev/test window" },
            @{ Name = "DB-DEV-01"; RG = "rg-database-development"; Sub = "Development"; Window = "Saturday"; Reason = "Database Dev - join existing dev/test window" },
            @{ Name = "TEST-SERVER-01"; RG = "rg-testing"; Sub = "Development"; Window = "Saturday"; Reason = "Test Server - join existing dev/test window" }
            # ... additional dev/test VMs
        )
    }
}

# Initialize counters
$totalProcessed = 0
$totalSuccess = 0
$totalFailed = 0

# Process each group
foreach ($groupName in $vmGroups.Keys) {
    $group = $vmGroups[$groupName]
    Write-Host "`n=== $groupName ===" -ForegroundColor Magenta
    Write-Host "Processing $($group.VMs.Count) VMs in this group" -ForegroundColor White

    foreach ($vmInfo in $group.VMs) {
        $window = $vmInfo.Window
        $vmName = $vmInfo.Name

        Write-Host "`n�️ $vmName β†’ $window maintenance window" -ForegroundColor Yellow
        Write-Host "   Reason: $($vmInfo.Reason)" -ForegroundColor Gray

        # Determine subscription ID from name
        $subscriptionId = switch ($vmInfo.Sub) {
            "Production" { (Get-AzSubscription -SubscriptionName "Production").Id }
            "DevTest" { (Get-AzSubscription -SubscriptionName "DevTest").Id }
            "Identity" { (Get-AzSubscription -SubscriptionName "Identity").Id }
            "DMZ" { (Get-AzSubscription -SubscriptionName "DMZ").Id }
        }

        # Create appropriate tags based on maintenance window
        $tags = @{
            "Owner" = "Contoso"
            "Updates" = "Azure Update Manager"
        }

        if ($window -eq "Saturday") {
            $tags["PatchWindow"] = "sat-09"  # Saturday 09:00 for dev/test
        } else {
            $tags["PatchWindow"] = $window.ToLower().Substring(0,3)  # mon, tue, wed, etc.
        }

        $result = Set-VMMaintenanceTags -VMName $vmInfo.Name -ResourceGroupName $vmInfo.RG -SubscriptionId $subscriptionId -Tags $tags -MaintenanceWindow $window

        $totalProcessed++
        if ($result) { 
            $totalSuccess++
            $newAssignments[$window]++
        } else { 
            $totalFailed++ 
        }
    }
}

Write-Host ""
Write-Host "=== TAGGING SUMMARY ===" -ForegroundColor Cyan
Write-Host "Total VMs processed: $totalProcessed" -ForegroundColor White
Write-Host "Successfully tagged: $totalSuccess" -ForegroundColor Green
Write-Host "Failed to tag: $totalFailed" -ForegroundColor Red

Write-Host ""
Write-Host "=== NEW MAINTENANCE WINDOW DISTRIBUTION ===" -ForegroundColor Cyan
Write-Host "VMs added to each maintenance window:" -ForegroundColor White

$newAssignments.GetEnumerator() | Sort-Object Name | ForEach-Object {
    if ($_.Value -gt 0) {
        $newTotal = $currentLoad[$_.Key] + $_.Value
        Write-Host "$($_.Key): +$($_.Value) VMs (total: $newTotal VMs)" -ForegroundColor Green
    }
}

Write-Host ""
Write-Host "=== FINAL MAINTENANCE WINDOW LOAD ===" -ForegroundColor Cyan
$finalLoad = @{}
$currentLoad.Keys | ForEach-Object {
    $finalLoad[$_] = $currentLoad[$_] + $newAssignments[$_]
}

$finalLoad.GetEnumerator() | Sort-Object Name | ForEach-Object {
    $status = if ($_.Value -le 8) { "Green" } elseif ($_.Value -le 12) { "Yellow" } else { "Red" }
    Write-Host "$($_.Key): $($_.Value) VMs" -ForegroundColor $status
}

$grandTotal = ($finalLoad.Values | Measure-Object -Sum).Sum
Write-Host "`nGrand Total: $grandTotal VMs across all maintenance windows" -ForegroundColor White

Write-Host ""
Write-Host "=== BUSINESS LOGIC APPLIED ===" -ForegroundColor Cyan
Write-Host "βœ… Critical systems spread across different days for resilience" -ForegroundColor Green
Write-Host "βœ… Domain Controllers distributed to avoid single points of failure" -ForegroundColor Green
Write-Host "βœ… Dev/Test systems consolidated to Saturday morning (existing pattern)" -ForegroundColor Green
Write-Host "βœ… Production workstations spread to minimize user impact" -ForegroundColor Green
Write-Host "βœ… Business applications distributed for operational continuity" -ForegroundColor Green
Write-Host "βœ… Load balancing maintained across the week" -ForegroundColor Green

Write-Host ""
Write-Host "=== VERIFICATION STEPS ===" -ForegroundColor Cyan
Write-Host "1. Verify tags in Azure Portal across all subscriptions" -ForegroundColor White
Write-Host "2. Check that critical systems are on different days" -ForegroundColor White
Write-Host "3. Confirm dev/test systems are in Saturday morning window" -ForegroundColor White
Write-Host "4. Review production systems distribution" -ForegroundColor White

Write-Host ""
Write-Host "=== AZURE RESOURCE GRAPH VERIFICATION QUERY ===" -ForegroundColor Cyan
Write-Host "Use this query to verify all VMs are now tagged:" -ForegroundColor White
Write-Host ""
Write-Host @"
Resources
| where type == "microsoft.compute/virtualmachines"
| where tags.Updates == "Azure Update Manager"
| project name, resourceGroup, subscriptionId, 
          patchWindow = tags.PatchWindow,
          owner = tags.Owner,
          updates = tags.Updates
| sort by patchWindow, name
| summarize count() by patchWindow
"@ -ForegroundColor Gray

if ($totalFailed -eq 0) {
    Write-Host ""
    Write-Host "οΏ½ ALL VMs SUCCESSFULLY TAGGED WITH INTELLIGENT DISTRIBUTION! οΏ½" -ForegroundColor Green
} else {
    Write-Host ""
    Write-Host "⚠️ Some VMs failed to tag. Please review errors above." -ForegroundColor Yellow
}

Write-Host ""
Write-Host "Script completed at $(Get-Date)" -ForegroundColor Cyan
Write-Host "Total runtime: $((Get-Date) - $scriptStart)" -ForegroundColor Gray

Key insight: I grouped VMs by function and criticality, not just by convenience. Domain controllers got spread across different days, dev/test systems joined the existing Saturday morning window, and production applications were distributed for business continuity.


🧰 Step 7 – Configure Azure Policy Prerequisites

Here's where things get interesting. Update Manager is built on compliance β€” but your VMs won't show up in dynamic scopes unless they meet certain prerequisites. Enter Azure Policy to save the day.

You'll need two specific built-in policies assigned at the subscription (or management group) level:

βœ… Policy 1: Set prerequisites for scheduling recurring updates on Azure virtual machines

What it does: This policy ensures your VMs have the necessary configurations to participate in Azure Update Manager. It automatically:

  • Installs the Azure Update Manager extension on Windows VMs
  • Registers required resource providers
  • Configures the VM to report its update compliance status
  • Sets the patch orchestration mode appropriately

Why this matters: Without this policy, VMs won't appear in Update Manager scopes even if they're tagged correctly. The policy handles all the "plumbing" automatically.

Assignment scope: Apply this at subscription or management group level to catch all VMs.

βœ… Policy 2: Configure periodic checking for missing system updates on Azure virtual machines

What it does: This is your compliance engine. It configures VMs to:

  • Regularly scan for available updates (but not install them automatically)
  • Report update status back to Azure Update Manager
  • Enable the compliance dashboard views in the portal
  • Provide the data needed for maintenance configuration targeting

Why this matters: This policy turns on the "update awareness" for your VMs. Without it, Azure Update Manager has no visibility into what patches are needed.

Assignment scope: Same as above β€” subscription or management group level.

🎯 Assigning the Policies

Step-by-step in Azure Portal:

  1. Navigate to Azure Policy
  2. Azure Portal β†’ Search "Policy" β†’ Select "Policy"

  3. Find the First Policy

  4. Left menu: Definitions
  5. Search: Set prerequisites for scheduling recurring updates
  6. Click on the policy title

  7. Assign the Policy

  8. Click Assign button
  9. Scope: Select your subscription(s)
  10. Basics: Leave policy name as default
  11. Parameters: Leave as default
  12. Remediation: βœ… Check "Create remediation task"
  13. Review + create

  14. Repeat for Second Policy

  15. Search: Configure periodic checking for missing system updates
  16. Follow same assignment process

⚠️ Important: Policy compliance can take 30+ minutes to evaluate and apply. Perfect time for that brew I mentioned earlier.

πŸ” Monitoring Compliance

Once assigned, you can track compliance in Azure Policy > Compliance. Look for:

  • Non-compliant VMs that need the extension installed
  • VMs that aren't reporting update status properly
  • Any policy assignment errors that need investigation

Learn more about Azure Policy for Update Management


πŸ§ͺ Step 8 – Create Dynamic Scopes in Update Manager

This is where it all comes together β€” and where the magic happens.

Dynamic scopes use those PatchWindow tags to assign VMs to the correct patch config automatically. No more manual VM assignment, no more "did we remember to add the new server?" conversations.

🎯 The Portal Dance

Unfortunately, as of writing, dynamic scopes can only be configured through the Azure portal β€” no PowerShell or ARM template support yet.

Why portal only? Dynamic scopes are still in preview, and Microsoft hasn't released the PowerShell cmdlets or ARM template schemas yet. This means you can't fully automate the deployment, but the functionality itself works perfectly.

Here's the step-by-step:

  1. Navigate to Azure Update Manager
  2. Portal β†’ All Services β†’ Azure Update Manager

  3. Access Maintenance Configurations

  4. Go to Maintenance Configurations (Preview)
  5. Select one of your configs (e.g., contoso-maintenance-config-vms-mon)

  6. Create Dynamic Scope

  7. Click Dynamic Scopes β†’ Add
  8. Name: DynamicScope-Monday-VMs
  9. Description: Auto-assign Windows VMs tagged for Monday maintenance

  10. Configure Scope Settings

  11. Subscription: Select your subscription(s)
  12. Resource Type: Microsoft.Compute/virtualMachines
  13. OS Type: Windows (create separate scopes for Linux if needed)

  14. Set Tag Filters

  15. Tag Name: PatchWindow
  16. Tag Value: mon (must match your maintenance config naming)
  17. Additional filters (optional):

    • Owner = Contoso
    • Updates = Azure Update Manager
  18. Review and Create

  19. Verify the filter logic
  20. Click Create

πŸ”„ Repeat for All Days

You'll need to create dynamic scopes for each maintenance configuration:

Maintenance Config Dynamic Scope Name Tag Filter
contoso-maintenance-config-vms-mon DynamicScope-Monday-VMs PatchWindow = mon
contoso-maintenance-config-vms-tue DynamicScope-Tuesday-VMs PatchWindow = tue
contoso-maintenance-config-vms-wed DynamicScope-Wednesday-VMs PatchWindow = wed
contoso-maintenance-config-vms-thu DynamicScope-Thursday-VMs PatchWindow = thu
contoso-maintenance-config-vms-fri DynamicScope-Friday-VMs PatchWindow = fri
contoso-maintenance-config-vms-sat DynamicScope-Saturday-VMs PatchWindow = sat-09
contoso-maintenance-config-vms-sun DynamicScope-Sunday-VMs PatchWindow = sun

πŸ” Verify Dynamic Scope Assignment

Once created, you can verify the scopes are working:

  1. In the Maintenance Configuration:
  2. Go to Dynamic Scopes
  3. Check Resources tab to see matched VMs
  4. Verify expected VM count matches your tagging
  5. Wait time: Allow 15-30 minutes for newly tagged VMs to appear

  6. What success looks like:

  7. Monday scope shows 5 VMs (WEB-PROD-01, DB-PROD-01, etc.)
  8. Saturday scope shows 5 VMs (WEB-DEV-01, DB-DEV-01, etc.)
  9. No VMs showing? Check tag case sensitivity and filters

  10. In Azure Resource Graph:

MaintenanceResources
| where type == "microsoft.maintenance/configurationassignments"
| extend vmName = tostring(split(resourceId, "/")[8])
| extend configName = tostring(properties.maintenanceConfigurationId)
| project vmName, configName, resourceGroup
| order by configName, vmName
  1. Troubleshoot empty scopes:
  2. Verify subscription selection includes all your VMs
  3. Check tag spelling: PatchWindow (case sensitive)
  4. Confirm resource type filter: Microsoft.Compute/virtualMachines
  5. Wait longer - it can take up to 30 minutes

⚠️ Common Gotchas

Tag Case Sensitivity: Dynamic scopes are case-sensitive. mon β‰  Mon β‰  MON

Subscription Scope: Ensure you've selected all relevant subscriptions in the scope configuration.

Resource Type Filter: Don't forget to set the resource type filter β€” without it, you'll match storage accounts, networking, etc.

Timing: It can take 15-30 minutes for newly tagged VMs to appear in dynamic scopes.

Dynamic scope configuration docs


πŸš€ Step 9 – Test & Verify (The Moment of Truth)

The acid test: does it actually patch stuff properly?

πŸŽͺ Proof of Concept Test

I started conservatively β€” scoped contoso-maintenance-config-vms-sun to a few non-critical VMs and let it run overnight on Sunday.

Monday morning verification:

  • βœ”οΈ Patch compliance dashboard: All green ticks
  • βœ”οΈ Reboot timing: Machines restarted within their 4-hour window (21:00-01:00)
  • βœ”οΈ Update logs: Activity logs showed expected patching behavior
  • βœ”οΈ Business impact: Zero helpdesk tickets on Monday morning

πŸ“Š Full Rollout Verification

Once confident with the Sunday test, I enabled all remaining dynamic scopes and monitored the week:

Key metrics tracked:

  • Patch compliance percentage across all VMs
  • Failed patch installations (and root causes)
  • Reboot timing adherence
  • Business hours impact (spoiler: zero)

πŸ” Monitoring & Validation Tools

Azure Update Manager Dashboard:

Azure Portal β†’ Update Manager β†’ Overview
- Patch compliance summary
- Recent patch installations
- Failed installations with details

Azure Resource Graph Queries:

// Verify all VMs have maintenance tags
Resources
| where type == "microsoft.compute/virtualmachines"
| where tags.Updates == "Azure Update Manager"
| project name, resourceGroup, subscriptionId, 
          patchWindow = tags.PatchWindow,
          owner = tags.Owner
| summarize count() by patchWindow
| order by patchWindow

// Check maintenance configuration assignments
MaintenanceResources
| where type == "microsoft.maintenance/configurationassignments"
| extend vmName = tostring(split(resourceId, "/")[8])
| extend configName = tostring(properties.maintenanceConfigurationId)
| project vmName, configName, subscriptionId
| summarize VMCount = count() by configName
| order by configName

PowerShell Verification:

# Quick check of maintenance configuration status
Get-AzMaintenanceConfiguration -ResourceGroupName "rg-maintenance-uksouth-001" | 
    Select-Object Name, MaintenanceScope, RecurEvery | 
    Format-Table -AutoSize

# Verify VM tag distribution
$subscriptions = Get-AzSubscription | Where-Object { $_.State -eq "Enabled" }
$tagSummary = @{}

foreach ($sub in $subscriptions) {
    Set-AzContext -SubscriptionId $sub.Id | Out-Null
    $vms = Get-AzVM | Where-Object { $_.Tags.PatchWindow }

    foreach ($vm in $vms) {
        $window = $vm.Tags.PatchWindow
        if (-not $tagSummary.ContainsKey($window)) {
            $tagSummary[$window] = 0
        }
        $tagSummary[$window]++
    }
}

Write-Host "=== VM DISTRIBUTION BY PATCH WINDOW ===" -ForegroundColor Cyan
$tagSummary.GetEnumerator() | Sort-Object Name | ForEach-Object {
    Write-Host "$($_.Key): $($_.Value) VMs" -ForegroundColor White
}

πŸ“ˆ Success Metrics

After two full weeks of operation:

  • Better control: Direct management of patch schedules and policies
  • Increased visibility: Real-time compliance dashboards vs. periodic reports
  • Reduced complexity: Native Azure tooling vs. third-party solutions

Monitor updates in Azure Update Manager


πŸ“ƒ Final Thoughts & Tips

βœ… Cost-neutral β€” No more third-party patch agents βœ… Policy-driven β€” Enforced consistency with Azure Policy βœ… Easily auditable β€” Tag-based scoping is clean and visible βœ… Scalable β€” New VMs auto-join patch schedules via tagging

⚠️ Troubleshooting Guide & Common Issues

Here's what I learned the hard way, so you don't have to:

Symptom Possible Cause Fix
VM not showing in dynamic scope Tag typo or case mismatch Verify PatchWindow tag exactly matches config name
Maintenance config creation fails Invalid duration format Use ISO 8601 format: "03:00" not "3 hours"
VM skipped during patching Policy prerequisites not met Check Azure Policy compliance dashboard
No updates applied despite schedule VM needs pending reboot Clear previous reboots, check update history
Dynamic scope shows zero VMs Wrong subscription scope Verify subscription selection in scope config
Extension installation failed Insufficient permissions Ensure VM contributor rights and resource provider registration
Policy compliance stuck at 0% Assignment scope too narrow Check policy is assigned at subscription level
VMs appear/disappear from scope Tag inconsistency Run tag verification script across all subscriptions

πŸ”§ Advanced Troubleshooting Commands

Check VM Update Readiness:

# Verify VM has required extensions and configuration
$vmName = "your-vm-name"
$rgName = "your-resource-group"

$vm = Get-AzVM -Name $vmName -ResourceGroupName $rgName -Status
$vm.Extensions | Where-Object { $_.Name -like "*Update*" -or $_.Name -like "*Maintenance*" }

Validate Maintenance Configuration:

# Test maintenance configuration is properly formed
$config = Get-AzMaintenanceConfiguration -ResourceGroupName "rg-maintenance-uksouth-001" -Name "contoso-maintenance-config-vms-mon"
Write-Host "Config Name: $($config.Name)"
Write-Host "Recurrence: $($config.RecurEvery)"
Write-Host "Duration: $($config.Duration)"
Write-Host "Start Time: $($config.StartDateTime)"
Write-Host "Timezone: $($config.TimeZone)"

Policy Compliance Deep Dive:

# Check specific VMs for policy compliance
$policyName = "Set prerequisites for scheduling recurring updates on Azure virtual machines"
$assignments = Get-AzPolicyAssignment | Where-Object { $_.Properties.DisplayName -eq $policyName }
foreach ($assignment in $assignments) {
    Get-AzPolicyState -PolicyAssignmentId $assignment.PolicyAssignmentId | 
        Where-Object { $_.ComplianceState -eq "NonCompliant" } |
        Select-Object ResourceId, ComplianceState, @{Name="Reason";Expression={$_.PolicyEvaluationDetails.EvaluatedExpressions.ExpressionValue}}
}

As always, comments and suggestions welcome over on GitHub or LinkedIn. If you've migrated patching in a different way, I'd love to hear how you approached it.

Share on Share on

πŸ’° Saving Azure Costs with Scheduled VM Start/Stop using Custom Azure Automation Runbooks

As part of my ongoing commitment to FinOps practices, I've implemented several strategies to embed cost-efficiency into the way we manage cloud infrastructure. One proven tactic is scheduling virtual machines to shut down during idle periods, avoiding unnecessary spend.

In this post, I’ll share how I’ve built out custom Azure Automation jobs to schedule VM start and stop operations. Rather than relying on Microsoft’s pre-packaged solution, I’ve developed a streamlined, purpose-built PowerShell implementation that provides maximum flexibility, transparency, and control.


✍️ Why I Chose Custom Runbooks Over the Prebuilt Solution

Microsoft provides a ready-made β€œStart/Stop VMs during off-hours” solution via the Automation gallery. While functional, it’s:

  • A bit over-engineered for simple needs,
  • Relatively opaque under the hood, and
  • Not ideal for environments where control and transparency are priorities.

My custom jobs:

  • Use native PowerShell modules within Azure Automation,
  • Are scoped to exactly the VMs I want via tags,
  • Provide clean logging and alerting, and
  • Keep things simple, predictable, and auditable.

πŸ› οΈ Step 1: Set Up the Azure Automation Account

πŸ”— Official docs: Create and manage an Azure Automation Account

  1. Go to the Azure Portal and search for Automation Accounts.
  2. Click + Create.
  3. Fill out the basics:
  4. Name: e.g. vm-scheduler
  5. Resource Group: Create new or select existing
  6. Region: Preferably where your VMs are located
  7. Enable System-Assigned Managed Identity
  8. Once created, go to the Automation Account and ensure the following modules are imported using the Modules blade in the Azure Portal:
  9. Az.Accounts
  10. Az.Compute

βœ… Tip: These modules can be added from the gallery in just a few clicks via the UIβ€”no scripting required.

πŸ’‘ Prefer scripting? You can also install them using PowerShell:

Install-Module -Name Az.Accounts -Force
Install-Module -Name Az.Compute -Force
  1. Assign the Virtual Machine Contributor role to the Automation Account's managed identity at the resource group or subscription level.

βš™οΈ CLI or PowerShell alternatives

# Azure CLI example to create the automation account
az automation account create \
  --name vm-scheduler \
  --resource-group MyResourceGroup \
  --location uksouth \
  --assign-identity

πŸ“… Step 2: Add VM Tags for Scheduling

Apply consistent tags to any VM you want the runbooks to manage.

Key Value
AutoStartStop devserver

You can use the Azure Portal or PowerShell to apply these tags.

βš™οΈ Tag VMs via PowerShell

$vm = Get-AzVM -ResourceGroupName "MyRG" -Name "myVM"
$vm.Tags["AutoStartStop"] = "devserver"
Update-AzVM -VM $vm -ResourceGroupName "MyRG"

πŸ“‚ Step 3: Create the Runbooks

πŸ”— Official docs: Create a runbook in Azure Automation

▢️ Create a New Runbook

  1. In your Automation Account, go to Process Automation > Runbooks.
  2. Click + Create a runbook.
  3. Name it something like Stop-TaggedVMs.
  4. Choose PowerShell as the type.
  5. Paste in the code below (repeat this process for the start runbook later).

πŸ”Ή Runbook Code: Auto-Stop Based on Tags

Param
(    
    [Parameter(Mandatory=$false)][ValidateNotNullOrEmpty()]
    [String]
    $AzureVMName = "All",

    [Parameter(Mandatory=$true)][ValidateNotNullOrEmpty()]
    [String]
    $AzureSubscriptionID = "<your-subscription-id>"
)

try {
    "Logging in to Azure..."
    # Authenticate using the system-assigned managed identity of the Automation Account
    Connect-AzAccount -Identity -AccountId "<managed-identity-client-id>"
} catch {
    Write-Error -Message $_.Exception
    throw $_.Exception
}

$TagName  = "AutoStartStop"
$TagValue = "devserver"

Set-AzContext -Subscription $AzureSubscriptionID

if ($AzureVMName -ne "All") {
    $VMs = Get-AzResource -TagName $TagName -TagValue $TagValue | Where-Object {
        $_.ResourceType -like 'Microsoft.Compute/virtualMachines' -and $_.Name -like $AzureVMName
    }
} else {
    $VMs = Get-AzResource -TagName $TagName -TagValue $TagValue | Where-Object {
        $_.ResourceType -like 'Microsoft.Compute/virtualMachines'
    }
}

foreach ($VM in $VMs) {
    Stop-AzVM -ResourceGroupName $VM.ResourceGroupName -Name $VM.Name -Verbose -Force
}

πŸ”— Docs: Connect-AzAccount with Managed Identity

πŸ”Ή Create the Start Runbook

Duplicate the above, replacing Stop-AzVM with Start-AzVM.

πŸ”— Docs: Start-AzVM


πŸ”— Docs: Create schedules in Azure Automation

  1. Go to the Automation Account > Schedules > + Add a schedule.
  2. Create two schedules:
  3. DailyStartWeekdays β€” Recurs every weekday at 07:30
  4. DailyStopWeekdays β€” Recurs every weekday at 18:30
  5. Go to each runbook > Link to schedule > Choose the matching schedule.

πŸ“Š You can get creative here: separate schedules for dev vs UAT, or different times for different departments.


πŸ§ͺ Testing Your Runbooks

You can test each runbook directly in the portal:

  • Open the runbook
  • Click Edit > Test Pane
  • Provide test parameters if needed
  • Click Start and monitor output

This is also a good time to validate:

  • The identity has permission
  • The tags are applied correctly
  • The VMs are in a stopped or running state as expected

πŸ“Š The Results

Even this lightweight automation has produced major savings in our environment. Non-prod VMs are now automatically turned off outside office hours, resulting in monthly compute savings of up to 60% without sacrificing availability during working hours.


🧠 Ideas for Further Enhancement

  • Pull tag values from a central config (e.g. Key Vault or Storage Table)
  • Add logic to check for active RDP sessions or Azure Monitor heartbeats
  • Alert via email or Teams on job success/failure
  • Track savings over time and visualize them

πŸ’­ Final Thoughts

If you’re looking for a practical, immediate way to implement FinOps principles in Azure, VM scheduling is a great place to start. With minimal setup and maximum flexibility, custom runbooks give you control without the complexity of the canned solutions.

Have you built something similar or extended this idea further? I’d love to hear about itβ€”drop me a comment or reach out on LinkedIn.

Stay tuned for more FinOps tips coming soon!

Share on Share on

⌚Enforcing Time Zone and DST Compliance on Windows Servers Using GPO and Scheduled Tasks


πŸ› οΈ Why This Matters

Time zone misconfigurations β€” especially those affecting Daylight Saving Time (DST) β€” can cause:

  • Scheduled tasks to run early or late
  • Timestamp mismatches in logs
  • Errors in time-sensitive integrations

Windows doesn’t always honour DST automatically, particularly in Azure VMs, automated deployments, or custom images.


πŸ” What’s Changed in 2025?

As of April 2025, we revised our approach to enforce time zone compliance in a cleaner, more manageable way:

  • 🧹 Removed all registry-based enforcement from existing GPOs
  • βš™οΈ Executed a one-time PowerShell script to correct servers incorrectly set to UTC (excluding domain controllers)
  • ⏲️ Updated the GPO to use a Scheduled Task that sets the correct time zone at startup (GMT Standard Time)

πŸ“‹ Audit Process: Time Zone and NTP Source Check

Before remediation, an audit was performed across the server estate to confirm the current time zone and time sync source for each host.

πŸ”Ž Time Zone Audit Script

# Set your target OU
$OU = "OU=Servers,DC=yourdomain,DC=local"

# Prompt for credentials once
$cred = Get-Credential

# Optional: output to file
$OutputCsv = "C:\Temp\TimeZoneAudit.csv"
$results = @()

# Get all enabled computer objects in the OU
$servers = Get-ADComputer -Filter {Enabled -eq $true} -SearchBase $OU -Properties Name | Select-Object -ExpandProperty Name

foreach ($server in $servers) {
    Write-Host "`nConnecting to $server..." -ForegroundColor Cyan
    try {
        $tzInfo = Invoke-Command -ComputerName $server -Credential $cred -ScriptBlock {
            $tz = Get-TimeZone
            $source = (w32tm /query /source) -join ''
            $status = (w32tm /query /status | Out-String).Trim()
            [PSCustomObject]@{
                ComputerName     = $env:COMPUTERNAME
                TimeZoneId       = $tz.Id
                TimeZoneDisplay  = $tz.DisplayName
                CurrentTime      = (Get-Date).ToString("yyyy-MM-dd HH:mm:ss")
                TimeSource       = $source
                SyncStatus       = $status
            }
        } -ErrorAction Stop

        $results += $tzInfo
    }
    catch {
        Write-Warning "Failed to connect to ${server}: $_"
        $results += [PSCustomObject]@{
            ComputerName     = $server
            TimeZoneId       = "ERROR"
            TimeZoneDisplay  = "ERROR"
            CurrentTime      = "N/A"
            TimeSource       = "N/A"
            SyncStatus       = "N/A"
        }
    }
}

# Output results
$results | Format-Table -AutoSize

# Save to CSV
$results | Export-Csv -NoTypeInformation -Path $OutputCsv
Write-Host "`nAudit complete. Results saved to $OutputCsv" -ForegroundColor Green

🧰 GPO-Based Scheduled Task (Preferred Solution)

Instead of relying on registry modifications, we now use a Scheduled Task deployed via Group Policy.

βœ… Task Overview

  • Trigger: At Startup
  • Action: Run powershell.exe
  • Arguments:
-Command "Set-TimeZone -Id 'GMT Standard Time'"

πŸ’‘ The GPO targets all domain-joined servers. Servers in isolated environments (e.g. DMZ) or not joined to the domain are excluded.


πŸ“Έ Scheduled Task Screenshots

GPO Task Properties - General Tab
Fig 1: Scheduled Task created via GPO Preferences

Scheduled Task Action Details
Fig 2: PowerShell command configuring the time zone


πŸ› οΈ One-Off Remediation Script: Setting the Time Zone

For servers identified as incorrect in the audit, the following script was used to apply the fix:

# List of servers to correct (e.g., from your audit results)
$servers = @(
    "server1",
    "server2",
    "server3"
)

# Prompt for credentials if needed
$cred = Get-Credential

foreach ($server in $servers) {
    Write-Host "Setting time zone on $server..." -ForegroundColor Cyan
    try {
        Invoke-Command -ComputerName $server -Credential $cred -ScriptBlock {
            Set-TimeZone -Id "GMT Standard Time"
        } -ErrorAction Stop

        Write-Host "βœ” $server: Time zone set to GMT Standard Time" -ForegroundColor Green
    }
    catch {
        Write-Warning "βœ– Failed to set time zone on ${server}: $_"
    }
}

πŸ” How to Verify Time Zone + DST Compliance

Use these PowerShell commands to verify:

Get-TimeZone
(Get-TimeZone).SupportsDaylightSavingTime

And for registry inspection (read-only):

Get-ItemProperty "HKLM:\SYSTEM\CurrentControlSet\Control\TimeZoneInformation" |
  Select-Object TimeZoneKeyName, DisableAutoDaylightTimeSet, DynamicDaylightTimeDisabled

Expected values:

  • TimeZoneKeyName: "GMT Standard Time"
  • DisableAutoDaylightTimeSet: 0
  • DynamicDaylightTimeDisabled: 0

🧼 Summary

To ensure consistent time zone configuration and DST compliance:

  • Use a GPO-based Scheduled Task to set GMT Standard Time at startup
  • Run a one-time audit and remediation script to fix legacy misconfigurations
  • Avoid registry edits β€” they’re no longer required
  • Validate using Get-TimeZone and confirm time sync via w32tm

πŸ“˜ Next Steps

  • [ ] Extend to Azure Arc or Intune-managed servers
  • [ ] Monitor for changes in Windows DST behaviour in future builds
  • [ ] Automate reporting to maintain compliance across environments

🧠 Final Thoughts

This GPO+script approach delivers a clean, scalable way to enforce time zone standards and DST logic β€” without relying on brittle registry changes.

Let me know if you'd like help adapting this for cloud-native or hybrid environments!


Share on Share on

⏲️ Configuring UK Regional Settings on Windows Servers with PowerShell

When building out cloud-hosted or automated deployments of Windows Servers, especially for UK-based organisations, it’s easy to overlook regional settings. But these seemingly small configurations β€” like date/time formats, currency symbols, or keyboard layouts β€” can have a big impact on usability, application compatibility, and user experience.

In this post, I’ll show how I automate this using a simple PowerShell script that sets all relevant UK regional settings in one go.


πŸ” Why Regional Settings Matter

Out-of-the-box, Windows often defaults to en-US settings:

  • Date format becomes MM/DD/YYYY
  • Decimal separators switch to . instead of ,
  • Currency symbols use $
  • Time zones default to US-based settings
  • Keyboard layout defaults to US (which can be infuriating!)

For UK-based organisations, this can:

  • Cause confusion in logs or spreadsheets
  • Break date parsing in scripts or apps expecting DD/MM/YYYY
  • Result in the wrong characters being typed (e.g., @ vs ")
  • Require manual fixing after deployment

Automating this ensures consistency across environments, saves time, and avoids annoying regional mismatches.


πŸ”§ Script Overview

I created a PowerShell script that:

  • Sets the system locale and input methods
  • Configures UK date/time formats
  • Applies the British English language pack (if needed)
  • Sets the time zone to GMT Standard Time (London)

The script can be run manually, included in provisioning pipelines, or dropped into automation tools like Task Scheduler or cloud-init processes.


βœ… Prerequisites

To run this script, you should have:

  • Administrator privileges
  • PowerShell 5.1+ (default on most supported Windows Server versions)
  • Optional: Internet access (if language pack needs to be added)

πŸ”Ή The Script: Set-UKRegionalSettings.ps1

# Set system locale and formats to English (United Kingdom)
Set-WinSystemLocale -SystemLocale en-GB
Set-WinUserLanguageList -LanguageList en-GB -Force
Set-Culture en-GB
Set-WinHomeLocation -GeoId 242
Set-TimeZone -Id "GMT Standard Time"

# Optional reboot prompt
Write-Host "UK regional settings applied. A reboot is recommended for all changes to take effect."

πŸš€ How to Use It

✈️ Option 1: Manual Execution

  1. Open PowerShell as Administrator
  2. Run the script:
.\Set-UKRegionalSettings.ps1

πŸ”’ Option 2: Include in Build Pipeline or Image

For Azure VMs or cloud images, consider running this as part of your deployment process via:

  • Custom Script Extension in ARM/Bicep
  • cloud-init or Terraform provisioners
  • Group Policy Startup Script

⚑ Quick Tips

  • Reboot after running to ensure all settings apply across UI and system processes.
  • For non-UK keyboards (like US physical hardware), you may also want to explicitly set InputLocale.
  • Want to validate the settings? Use:
Get-WinSystemLocale
Get-Culture
Get-WinUserLanguageList
Get-TimeZone

πŸ“‚ Registry Verification: Per-User and Default Settings

Registry Editor Screenshot

If you're troubleshooting or validating the configuration for specific users, regional settings are stored in the Windows Registry under:

πŸ‘€ For Each User Profile

HKEY_USERS\<SID>\Control Panel\International

You can find the user SIDs by looking under HKEY_USERS or using:

Get-ChildItem Registry::HKEY_USERS

🧡 For New Users (Default Profile)

HKEY_USERS\.DEFAULT\Control Panel\International

This determines what settings new user profiles inherit on first logon.

You can script changes here if needed, but always test carefully to avoid corrupting profile defaults.


🌟 Final Thoughts

Small tweaks like regional settings might seem minor, but they go a long way in making your Windows Server environments feel localised and ready for your users.

Automating them early in your build pipeline means one less thing to worry about during post-deployment configuration.

Let me know if you want a version of this that handles multi-user scenarios or works across multiple OS versions!

Share on Share on

πŸ•΅οΈ Replacing SAS Tokens with User Assigned Managed Identity (UAMI) in AzCopy for Blob Uploads

Using Shared Access Signature (SAS) tokens with azcopy is common β€” but rotating tokens and handling them securely can be a hassle. To improve security and simplify our automation, I recently replaced SAS-based authentication in our scheduled AzCopy jobs with Azure User Assigned Managed Identity (UAMI).

In this post, I’ll walk through how to:

  • Replace AzCopy SAS tokens with managed identity authentication
  • Assign the right roles to the UAMI
  • Use azcopy login to authenticate non-interactively
  • Automate the whole process in PowerShell

πŸ” Why Remove SAS Tokens?

SAS tokens are useful, but:

  • πŸ”‘ They’re still secrets β€” and secrets can be leaked
  • πŸ“… They expire β€” which breaks automation when not rotated
  • πŸ” They grant broad access β€” unless scoped very carefully

Managed Identity is a much better approach when the copy job is running from within Azure (like an Azure VM or Automation account).


🌟 Project Goal

Replace the use of SAS tokens in an AzCopy job that uploads files from a local UNC share to Azure Blob Storage β€” by using a User Assigned Managed Identity.


βœ… Prerequisites

To follow along, you’ll need:

  • A User Assigned Managed Identity (UAMI)
  • A Windows Server or Azure VM to run the copy job
  • Access to a local source folder or UNC share (e.g., \\fileserver\\data\\export\\)
  • AzCopy v10.7+ installed on the machine
  • Azure RBAC permissions to assign roles

ℹ️ Check AzCopy Version: Run azcopy --version to ensure you're using v10.7.0 or later, which is required for --identity-client-id support.


πŸ”§ Step-by-Step Setup

πŸ› οΈ Step 1: Create the UAMI

βœ… CLI
az identity create \
  --name my-azcopy-uami \
  --resource-group my-resource-group \
  --location <region>
βœ… Portal
  1. Go to Managed Identities in the Azure Portal
  2. Click + Create and follow the wizard

πŸ–‡οΈ Step 2: Assign the UAMI to the Azure VM

AzCopy running on a VM must be able to assume the identity. Assign the UAMI to your VM:

βœ… CLI
az vm identity assign \
  --name my-vm-name \
  --resource-group my-resource-group \
  --identities my-azcopy-uami
βœ… Portal
  1. Navigate to the Virtual Machines blade
  2. Select the VM running your AzCopy script
  3. Under Settings, click Identity
  4. Go to the User assigned tab
  5. Click + Add, select your UAMI, then click Add

πŸ” Step 3: Assign RBAC Permissions to UAMI

For AzCopy to function correctly with a UAMI, the following role assignments are recommended:

  • Storage Blob Data Contributor: Required for read/write blob operations
  • Storage Blob Data Reader: (Optional) For read-only scenarios or validation scripts
  • Reader: (Optional) For browsing or metadata-only permissions on the storage account

⏳ RBAC Tip: It may take up to 5 minutes for role assignments to propagate fully. If access fails initially, wait and retry.

βœ… CLI
az role assignment create \
  --assignee <client-id-or-object-id> \
  --role "Storage Blob Data Contributor" \
  --scope "/subscriptions/<sub-id>/resourceGroups/<rg>/providers/Microsoft.Storage/storageAccounts/<storage-account>/blobServices/default/containers/<container-name>"

az role assignment create \
  --assignee <client-id-or-object-id> \
  --role "Storage Blob Data Reader" \
  --scope "/subscriptions/<sub-id>/resourceGroups/<rg>/providers/Microsoft.Storage/storageAccounts/<storage-account>"

az role assignment create \
  --assignee <client-id-or-object-id> \
  --role "Reader" \
  --scope "/subscriptions/<sub-id>/resourceGroups/<rg>/providers/Microsoft.Storage/storageAccounts/<storage-account>"
βœ… Portal
  1. Go to your Storage Account in the Azure Portal
  2. Click on the relevant container (or stay at the account level for broader scope)
  3. Open Access Control (IAM)
  4. Click + Add role assignment
  5. Repeat this for each role:
  6. Select Storage Blob Data Contributor, assign to your UAMI, and click Save
  7. Select Storage Blob Data Reader, assign to your UAMI, and click Save
  8. Select Reader, assign to your UAMI, and click Save

πŸ§ͺ Step 4: Test AzCopy Login Using UAMI

$clientId = "<your-uami-client-id>"
& "C:\azcopy\azcopy.exe" login --identity --identity-client-id $clientId

You should see a confirmation message that AzCopy has successfully logged in.

πŸ” To verify AzCopy is authenticated with the correct identity, you can run:

azcopy env

This will show the login type and confirm whether the token is being sourced from the Managed Identity.


πŸ“ Step 5: Upload Files Using AzCopy + UAMI

Here's the PowerShell script that copies all files from a local share to the Blob container:

$clientId = "<your-uami-client-id>"

# Login with Managed Identity
& "C:\azcopy\azcopy.exe" login --identity --identity-client-id $clientId

# Run the copy job
& "C:\azcopy\azcopy.exe" copy \
  "\\\\fileserver\\data\\export\\" \
  "https://<your-storage-account>.blob.core.windows.net/<container-name>" \
  --overwrite=true \
  --from-to=LocalBlob \
  --blob-type=Detect \
  --put-md5 \
  --recursive \
  --log-level=INFO

πŸ’‘ UNC Note: Double backslashes are used in PowerShell to represent UNC paths properly.

This script can be scheduled using Task Scheduler or run on demand.


⏱️ Automate with Task Scheduler (Optional)

To automate the job:

  1. Open Task Scheduler on your VM
  2. Create a New Task (not a Basic Task)
  3. Under General, select "Run whether user is logged on or not"
  4. Under Actions, add a new action to run powershell.exe
  5. Set the arguments to point to your .ps1 script
  6. Ensure the AzCopy path is hardcoded in your script

πŸš‘ Troubleshooting Common Errors

❌ 403 AuthorizationPermissionMismatch
  • Usually means the identity doesn’t have the correct role or the role hasn’t propagated yet
  • Double-check:
  • UAMI is assigned to the VM
  • UAMI has Storage Blob Data Contributor on the correct container
  • Wait 2–5 minutes and try again
❌ azcopy : The term 'azcopy' is not recognized
  • AzCopy is not in the system PATH
  • Solution: Use the full path to azcopy.exe, like C:\azcopy\azcopy.exe

πŸ›‘οΈ Benefits of Switching to UAMI

  • βœ… No secrets or keys stored on disk
  • βœ… No manual token expiry issues
  • βœ… Access controlled via Azure RBAC
  • βœ… Easily scoped and auditable

🧼 Final Thoughts

Replacing AzCopy SAS tokens with UAMI is one of those small wins that pays dividends over time. Once set up, it's secure, robust, and hands-off.

Let me know if you'd like a variant of this that works from Azure Automation or a hybrid worker!


Share on Share on

πŸ“’ Uninstalling PaperCut MF Client via Intune – A Step-by-Step Guide πŸš€

πŸ” Scenario Overview

Managing software across an enterprise can be a headache, especially when it comes to removing outdated applications. Recently, I needed to uninstall the PaperCut MF Client from multiple Windows PCs in my environment. The challenge? Ensuring a clean removal without user intervention and no leftover files.

Rather than relying on manual uninstallation, we used Microsoft Intune to deploy a PowerShell script that handles the removal automatically. This blog post details the full process, from script development to deployment and testing.


🎯 The Goal

βœ… Uninstall the PaperCut MF Client silently
βœ… Ensure no residual files are left behind
βœ… Deploy the solution via Intune as a PowerShell script (NOT as a Win32 app)
βœ… Test both locally and remotely before large-scale deployment


πŸ›  Step 1: Writing the Uninstall Script

We first created a PowerShell script to:

  1. Stop PaperCut-related processes
  2. Run the built-in uninstaller (unins000.exe) if present
  3. Use MSIEXEC to remove the MSI-based install
  4. Forcefully delete any remaining files and registry entries

πŸ“ The Uninstall Script

# Define variables
$UninstallExePath = "C:\Program Files (x86)\PaperCut MF Client\unins000.exe"
$MsiProductCode = "{5B4B80DE-34C4-11E9-9CA9-F53BB8A68831}"  # Replace with actual Product Code
$LogFile = "C:\ProgramData\Custom-Intune-Scripts\Papercut-Uninstall.log"
$InstallPath = "C:\Program Files (x86)\PaperCut MF Client"

# Function to log output
Function Write-Log {
    param ([string]$Message)
    $TimeStamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    "$TimeStamp - $Message" | Out-File -Append -FilePath $LogFile
}

Write-Log "Starting PaperCut MF Client uninstallation process."

# Stop any running PaperCut processes before uninstalling
$Processes = @("pc-client", "pc-client-java", "pc-client-local-cache")  # Common PaperCut processes
foreach ($Process in $Processes) {
    if (Get-Process -Name $Process -ErrorAction SilentlyContinue) {
        Write-Log "Stopping process: $Process"
        Stop-Process -Name $Process -Force -ErrorAction SilentlyContinue
    }
}

# Check if unins000.exe exists
if (Test-Path $UninstallExePath) {
    Write-Log "Found unins000.exe at $UninstallExePath. Initiating uninstallation."
    Start-Process -FilePath $UninstallExePath -ArgumentList "/SILENT" -NoNewWindow -Wait
    Write-Log "Uninstallation process completed using unins000.exe."
} else {
    Write-Log "unins000.exe not found. Attempting MSI uninstallation using Product Code $MsiProductCode."
    Start-Process -FilePath "msiexec.exe" -ArgumentList "/x $MsiProductCode /qn /norestart" -NoNewWindow -Wait
}

# Forcefully delete the remaining installation folder
if (Test-Path $InstallPath) {
    Write-Log "Residual files found at $InstallPath. Attempting to remove forcefully."
    takeown /F "$InstallPath" /R /D Y | Out-Null
    icacls "$InstallPath" /grant Administrators:F /T /C /Q | Out-Null
    Remove-Item -Path $InstallPath -Recurse -Force -ErrorAction SilentlyContinue
    if (-not (Test-Path $InstallPath)) {
        Write-Log "SUCCESS: Residual files successfully removed."
    } else {
        Write-Log "ERROR: Failed to remove residual files. Manual intervention may be required."
    }
} else {
    Write-Log "No residual files found."
}

Write-Log "PaperCut MF Client uninstallation script execution finished."

πŸ§ͺ Step 2: Testing the Script Locally

Before deploying via Intune, it's best to test locally:

  1. Open PowerShell as Administrator
  2. Run the script manually:
powershell.exe -ExecutionPolicy Bypass -File "C:\Path\To\Script.ps1"
  1. Verify:
  2. Check C:\Program Files (x86)\PaperCut MF Client to confirm deletion
  3. Check C:\ProgramData\AXA-Custom-Intune-Scripts\Papercut-Uninstall.log for success logs

🌍 Step 3: Running the Script on a Remote PC

If you need to test the script remotely before deploying via Intune:

$RemotePC = "COMPUTER-NAME"  # Change this to the target PC name
Invoke-Command -ComputerName $RemotePC -FilePath "C:\Path\To\Script.ps1" -Credential (Get-Credential)

πŸ“‘ Step 4: Deploying via Intune

Instead of packaging the script as a .intunewin file, we will deploy it as a PowerShell script in Intune.

🎯 Steps to Deploy in Intune

  1. Go to Microsoft Endpoint Manager admin center (endpoint.microsoft.com)
  2. Navigate to Devices > Scripts
  3. Click Add > Windows 10 and later
  4. Upload the PowerShell script (Papercut-Uninstall.ps1)
  5. Configure settings:
  6. Run script using the logged-on credentials? β†’ No (runs as SYSTEM)
  7. Enforce script signature check? β†’ No
  8. Run script in 64-bit PowerShell Host? β†’ Yes
  9. Assign the script to device groups (not users)
  10. Monitor deployment logs in Intune

πŸ“Œ Final Thoughts

By using Intune and PowerShell, we successfully automated the silent uninstallation of PaperCut MF Client. This approach ensures a zero-touch removal with no residual files, keeping endpoints clean and manageable. πŸš€

Got questions or need enhancements? Drop them in the comments! 😊

Share on Share on