Script hygiene standard for client tenants
Five rules every PowerShell script we run in a client tenant follows, so it's safe, auditable and hard to point at the wrong tenant.
The rules
- No required Tenant ID. The script runs against whatever tenant you sign in to. Hard-coded or required tenant IDs get copied between clients and pointed at the wrong one.
- Disconnect first. Start every script with
Disconnect-MgGraph(andDisconnect-ExchangeOnline -Confirm:$falsewhere relevant). Otherwise you can silently reuse yesterday’s session in another client’s tenant. - Print who and where. After connecting, print the signed-in account and tenant, and pause for confirmation:
$ctx = Get-MgContext
Write-Host "Connected as $($ctx.Account) to tenant $($ctx.TenantId)"
Read-Host "Correct tenant? Press Enter to continue, Ctrl+C to stop"
- Read-only by default. Anything that changes state needs an explicit switch (for example
-Apply) and should support-WhatIf. - Export CSV. Results go to a timestamped CSV, so there’s evidence and something to hand the client.
Also
Seeing this in your environment?
We can check for this, and everything around it, as part of an audit.