Skip to content
M365-07 Field-tested

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

  1. 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.
  2. Disconnect first. Start every script with Disconnect-MgGraph (and Disconnect-ExchangeOnline -Confirm:$false where relevant). Otherwise you can silently reuse yesterday’s session in another client’s tenant.
  3. 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"
  1. Read-only by default. Anything that changes state needs an explicit switch (for example -Apply) and should support -WhatIf.
  2. Export CSV. Results go to a timestamped CSV, so there’s evidence and something to hand the client.

Also

  • Depend on Microsoft.Graph.Authentication only and use Invoke-MgGraphRequest (M365-04).
  • Read CSVs with BOM handling (M365-26).

Seeing this in your environment?

We can check for this, and everything around it, as part of an audit.

Ask us about M365-07

Find out what's really going on in your tenant.

Tell us what you run and what's worrying you. We'll recommend the right audit, and tell you honestly if you don't need one.