Skip to content
All articles
Automation 12 min read15 Jul 2026

PowerShell Automation & Scripting for Enterprise IT

Production PowerShell automation — best practices, Exchange Online automation, Azure Automation runbooks, Active Directory automation, bulk user management and reporting scripts with the Microsoft Graph SDK.

PowerShellAzure AutomationMicrosoft GraphActive DirectoryAutomation

Treat PowerShell like production code

The difference between a script that works and one that scales is engineering discipline. Use modules with verb-noun function names, parameter sets and approved verbs. Declare [CmdletBinding()] so functions support -Verbose, -WhatIf and -Confirm for free. Validate parameters with [ValidateNotNullOrEmpty] and [ValidateRange]. Separate "do work" functions from orchestration so the same functions run in runbooks, scheduled tasks and interactive sessions.

  • Use [CmdletBinding()] and approved verbs
  • Validate parameters; support -WhatIf on destructive ops
  • Separate worker functions from orchestration
  • Version scripts in Git, not in a shared folder

Error handling and logging

Set $ErrorActionPreference = "Stop" in modules so failures are caught, not silently swallowed. Wrap external calls in try/catch and log the exception. Write structured logs — timestamp, tenant, action, result — to a CSV, log file or webhook into your ticketing system so you can audit what a scheduled runbook actually did.

PowerShell — Structured try/catch with logging
$ErrorActionPreference = "Stop"
function Invoke-LoggedAction {
  param([string]$Action, [scriptblock]$Work)
  try {
    & $Work
    [PSCustomObject]@{ Time = (Get-Date); Action = $Action; Result = "OK" } |
      Export-Csv -Path "$env:TEMP\ops.log" -Append -NoTypeInformation
  } catch {
    [PSCustomObject]@{ Time = (Get-Date); Action = $Action; Result = $_.Exception.Message } |
      Export-Csv -Path "$env:TEMP\ops.log" -Append -NoTypeInformation
    throw
  }
}

Exchange Online automation scripts

Exchange Online PowerShell v3 (ExchangeOnlineManagement) is the modern module — use app-only auth with a certificate for unattended automation. Common high-value scripts: bulk mailbox permission audits, forwarding rule detection (a data-exfiltration vector), retention policy application, and mailbox quota reporting. Connect with -CertificateThumbprint and a registered Entra ID app for runbook use.

PowerShell — Detect hidden forwarding rules (app-only)
Connect-ExchangeOnline -CertificateThumbprint $thumb `
  -AppId $appId -Organization $tenant -ShowBanner:$false
Get-Mailbox -ResultSize Unlimited | ForEach-Object {
  Get-InboxRule -Mailbox $_.UserPrincipalName |
    Where-Object { $_.RedirectTo -or $_.ForwardTo -or $_.ForwardAsAttachmentTo } |
    Select-Object MailboxOwnerId, Name, RedirectTo, ForwardTo, Enabled
} | Export-Csv -Path "forwarding-rules.csv" -NoTypeInformation

Azure Automation runbooks

Azure Automation is the natural host for scheduled PowerShell. Use a managed identity (not a stored service-account password) to authenticate to Graph, Azure and other services. Store secrets in Azure Key Vault and reference them from the runbook. Use schedules and webhooks to trigger runbooks, and link them to Azure Monitor alerts for error notification.

  • Use managed identities — no stored passwords
  • Store secrets in Key Vault, reference from the runbook
  • Trigger via schedules or webhooks
  • Alert on runbook failures via Azure Monitor

Active Directory automation

AD automation pays back fastest in joiner-mover-leaver. A single idempotent script reads the HR feed, creates the AD user with the right attributes, adds to groups, provisions the mailbox, and opens the ticket. Run it from Azure Automation with a managed identity. Use the ActiveDirectory module for on-prem and Microsoft Graph for Entra ID — the legacy AzureAD and MSOnline modules are deprecated.

PowerShell — Idempotent new-hire provisioning
function New-ProvisionedUser {
  param([string]$GivenName, [string]$Surname, [string]$Title, [string]$Dept)
  $upn = ("{0}.{1}@corp.contoso.com" -f $GivenName, $Surname).ToLower()
  if (Get-ADUser -Filter "UserPrincipalName -eq '$upn'" -ErrorAction SilentlyContinue) {
    Write-Verbose "User $upn exists — skipping"; return
  }
  New-ADUser -Name "$GivenName $Surname" -GivenName $GivenName -Surname $Surname `
    -Title $Title -Department $Dept -UserPrincipalName $upn `
    -Path "OU=Staff,DC=corp,DC=contoso,DC=com" -Enabled $true `
    -AccountPassword (ConvertTo-SecureString "Temp!Pass123" -AsPlainText -Force)
  Add-ADGroupMember -Identity "GG-$Dept" -Members $upn
}

Bulk user management and reporting

Bulk operations are where PowerShell earns its keep — but they are also where mistakes scale. Always use -WhatIf first, process in batches with a progress indicator, and write a results CSV so you can audit and roll back. For reporting, schedule scripts that export to a SharePoint list, a Power BI dataset or an email summary so the data reaches the people who act on it.

ScenarioModuleApproach
Bulk licence assignmentMicrosoft.GraphGroup-based licensing, then audit
Stale account reportActiveDirectoryLastLogonDate > 90d, export CSV
Group membership syncActiveDirectory + GraphDiff source/target, add/remove
Mailbox quota reportExchangeOnlineManagementExport to CSV + email summary

Lessons learned

  • Move off MSOnline/AzureAD to Microsoft Graph SDK now
  • Use managed identities in Azure Automation — no stored passwords
  • Make JML scripts idempotent so re-runs are safe
  • Always -WhatIf before a bulk destructive operation

Written by

Jamshed Alam

Global MSP & IT Infrastructure Consultant with 20 years across Exchange, Microsoft 365, Azure, security and automation. Available for project and contract work worldwide.

Share
JA

Jamshed Alam

Global MSP | IT Infrastructure Consultant | Cloud & Automation Expert · Lahore, Pakistan

EmailLinkedInUpworkGuru© 2026 Jamshed Alam