Structure scripts for reuse
Treat PowerShell like production code. Use modules with verb-noun function names, parameter sets, and approved verbs. Separate the "do work" functions from the "orchestrate" script so the same functions can be reused by runbooks, scheduled tasks and interactive sessions.
Always use parameter validation ([ValidateNotNullOrEmpty], [ValidateRange]) and declare [CmdletBinding()] so your functions support -Verbose, -WhatIf and -Confirm for free.
Error handling and logging
Use try/catch with $ErrorActionPreference = "Stop" so failures are caught, not silently swallowed. Log to a structured sink — a CSV, a log file, or a webhook into your ticketing system — so you can audit what a scheduled runbook actually did.
- Set $ErrorActionPreference = "Stop" in modules
- Wrap external calls in try/catch and log the exception
- Write structured logs with timestamp, tenant, action and result
- Use -WhatIf on destructive operations
Joiner-mover-leaver automation
The highest-value automation in any MSP is the joiner-mover-leaver (JML) workflow. A single script reads the HR feed, creates the Entra ID user, assigns licences by group, provisions the mailbox, adds to Teams channels, and opens the ticket — all idempotently so re-runs do not duplicate work.
Run it from Azure Automation with a managed identity so no service-account passwords are stored. Use the Microsoft Graph PowerShell SDK for M365 operations; it replaces the deprecated Azure AD and MSOnline modules.
Lessons learned
- Move off MSOnline/AzureAD modules to Microsoft Graph SDK now
- Use managed identities in Azure Automation — no stored passwords
- Make JML scripts idempotent so re-runs are safe
- Version scripts in Git, not in a shared folder
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.