A client reported that guest users, people from partner organisations invited into their Microsoft 365 tenant, were getting "your password will expire" emails. Guests sign in with their own organisation's account. There is no password for them to change, and the links in the email do nothing for them. It looks harmless, but a security-flavoured email that makes no sense to its recipient teaches people to ignore that kind of email, which is the opposite of what you want.
Scope note. Done on 19 November 2026 for a client with Microsoft Entra ID, Microsoft Entra Domain Services and a long-standing reminder script. Domain names, server names and paths below are generic.
The Setup
The reminders came from a PowerShell script, the kind widely shared in admin communities and adapted many times over, running on a management server joined to the client's Entra Domain Services managed domain:
- A daily scheduled task, running as SYSTEM.
Get-ADUseragainst the managed domain: enabled users whose passwords expire and haven't yet.- For each, days until expiry from
PasswordLastSetplus the maximum password age; if that number is in a list of reminder days, send an email. - Email sent through Amazon SES over SMTP, with the SMTP credential stored in a file next to the script.
The important detail is the second bullet. The script never talks to Entra ID. It reads the Domain Services copy of the directory.
Why Guests Were Getting Emails
Entra Domain Services synchronises users one way from Entra ID into the managed domain, into the AADDC Users container. Guests come along with everyone else. So to Get-ADUser, a guest is just another enabled user with a password policy.
In Entra ID, guests are easy to spot: their user principal name contains #EXT#. In the managed domain, that marker isn't there. A search for #EXT# in Domain Services returned nothing at all. The one dependable signal people reach for simply doesn't exist where this script looks.
Check the Data Before Choosing a Rule
The tempting fix was to skip any username containing "ext". Before changing anything, I checked what that would catch, read-only, with Microsoft Graph:
| Check in Entra ID | Result |
|---|---|
Guests with #EXT# in the user principal name | Over 99% |
| Guests without it | A single account: a cloud account with a real password in the tenant, not an invited guest |
Members with #EXT# | None |
Members whose username starts with ext | A handful, all real staff who need their reminders |
| Accounts with no user type set | None |
That settled it. An "ext" filter would have quietly stopped reminders for real staff, the people most likely to need them, and nobody would have noticed until their passwords expired. Filtering on #EXT# wasn't possible in Domain Services. I needed a rule that didn't depend on how guests look at all.
The checks, all read-only. In Entra ID:
Connect-MgGraph -Scopes "User.Read.All"
$all = Get-MgUser -All -Property UserPrincipalName,UserType
$guests = @($all | Where-Object { $_.UserType -eq 'Guest' })
$members = @($all | Where-Object { $_.UserType -eq 'Member' })
"Guests: " + $guests.Count
"Guests without #EXT#: " + @($guests | Where-Object { $_.UserPrincipalName -notlike '*#EXT#*' }).Count
"Members with #EXT#: " + @($members | Where-Object { $_.UserPrincipalName -like '*#EXT#*' }).Count
"Members starting 'ext': " + @($members | Where-Object { $_.UserPrincipalName -like 'ext*' }).Count
"UserType blank: " + @($all | Where-Object { [string]::IsNullOrEmpty($_.UserType) }).Count
And in the managed domain, on the management server:
# Guests with #EXT# in Domain Services (this returned 0)
@(Get-ADUser -Filter "UserPrincipalName -like '*#EXT#*'").Count
# Everyone a domain filter would skip, grouped by email domain
Get-ADUser -Filter { (Enabled -eq 'True') -and (PasswordNeverExpires -eq 'False') } -Properties EmailAddress |
Where-Object { $_.EmailAddress -notlike '*@contoso.com' } |
Group-Object { ($_.EmailAddress -split '@')[-1] } | Sort-Object Count -Descending |
Format-Table Count, Name
The second query is the one to read before trusting any allow-list: it shows every domain you are about to stop emailing, so a forgotten legacy domain shows up before its users miss a reminder. Its output lists partner domains, so keep it out of tickets and chats.
The Fix: An Allow-List of Your Own Domains
Guests keep their own email addresses, on their own organisations' domains. Staff have addresses on the client's own domains. So the rule became: only email addresses on our own domains.
The change is to the filter at the end of the Get-ADUser line:
# Before
Where-Object { $_.PasswordExpired -eq $false }
# After
Where-Object { ($_.PasswordExpired -eq $false) -and
(($_.EmailAddress -like '*@contoso.com') -or
($_.EmailAddress -like '*@fabrikam.com') -or
($_.EmailAddress -like '*@adatum.com')) }
Three details make this safe:
-likeis case-insensitive, soExt.Someone@Contoso.comstill matches.- The pattern includes the
@, so a look-alike such asnotcontoso.comdoesn't. - It is an allow-list. A new partner, a new guest, or a change in how Domain Services names guests can't leak back in.
One side effect, deliberately accepted: users with no email address in the directory are now skipped. The script used to fall back to their proxy addresses. For this client, every real user has an email address, so nothing is lost, but it is the kind of behaviour change worth writing down.
The one guest without #EXT#, a cloud account with its own password, is worth a separate look: if its email address happens to be on one of your domains, it will still get reminders. A read-only check shows only what matters:
Get-MgUser -All -Property UserPrincipalName,UserType,Mail,AccountEnabled |
Where-Object { $_.UserType -eq 'Guest' -and $_.UserPrincipalName -notlike '*#EXT#*' } |
ForEach-Object {
[pscustomobject]@{
Enabled = $_.AccountEnabled
MailDomain = if ($_.Mail) { ($_.Mail -split '@')[-1] } else { '(none)' }
OnOurDomains = [bool]($_.Mail -match '@(contoso\.com|fabrikam\.com|adatum\.com)$')
}
}
If OnOurDomains is True, fix the account rather than the script: make it a member if it is staff, disable it if it is unused.
While in there, I also added an earlier first reminder, at 24 days, so people get more notice. That is a one-number change, and the only other change made.
Testing Without Emailing Anyone Else
A reminder script is awkward to test: run it as it is and it emails real people. I tested with a copy:
- The reminder days widened to every day up to 20, so it would fire for my own account.
- The filter narrowed to my own account only, by adding
-and ($_.SamAccountName -eq 'myaccount'). - Its own folder, its own credential file and its own log, so nothing touched the live files.
The reminder arrived. Then the old script was kept as a .bak, the new one put live, and a runbook written for the client. To test the live scheduled task later, set the reminder days to exactly the number of days left on your own password, run the task from Task Scheduler, check the email and a result of 0x0, then set it back. Anyone else at that same number of days gets a reminder too, which is harmless.
The Credential File Traps
Most of the time went here, and none of it is specific to this client.
- The file only works for the account that made it.
Export-Clixmlencrypts the password with Windows DPAPI for the user who ran it. The live file was made by SYSTEM, so my test run failed with Key not valid for use in specified state. It can't be copied to another account or another server either. - Recreating it as SYSTEM needs PsExec.
runascan't run as SYSTEM;psexec -accepteula -s -i powershell.execan. Checkwhoamisaysnt authority\systemin the new window before saving. PsExec running as SYSTEM looks exactly like an attacker's tool to endpoint protection, so tell the security team before you do it. - An empty credential is still saved.
Get-Credentialopens a pop-up that often lands behind the console window. Close it without typing anything and the script still writes a credential file, an empty one, and every send then fails with Authentication required. - The SES SMTP password is not the AWS secret key. SES SMTP credentials are an IAM access key ID as the user name and a password derived from the secret key. If a password manager holds both, the one to use is the converted SMTP password.
- You can trace an unknown key without its secret. The SMTP user name is an AWS access key ID (
AKIA…). The steps are below. - Graph and Exchange modules can clash.
Connect-MgGraphrefused to load because the Exchange Online module had already loaded its own copy ofAzure.Core.dllthrough the PowerShell profile. Starting PowerShell with-NoProfilefixed it.
To check a credential file without exposing it. Run as yourself against the live file, "created by another account" is the healthy answer, because it belongs to SYSTEM:
$f = "C:\Scripts\PasswordExpiry\EmailExpiry.cred"
if (Test-Path $f) {
try { $c = Import-Clixml $f -ErrorAction Stop; "exists, contains credential = " + [bool]$c }
catch { "exists, created by another account" }
} else { "missing" }
Tracing the SES key to its AWS account and user
Nobody had recorded which AWS account and IAM user the SES sender lived in. None of these steps need the secret; the profiles are whichever AWS CLI profiles you already have (AWS CLI reference):
# 1. Which account owns the key (any profile with valid credentials can ask)
aws --profile <profile> sts get-access-key-info --access-key-id AKIA...
# 2. Which of your profiles is that account
for p in $(aws configure list-profiles); do
echo "$p: $(aws --profile $p sts get-caller-identity --query Account --output text)"
done
# 3. Which IAM user owns the key, using the profile that matched
aws --profile <profile> iam get-access-key-last-used --access-key-id AKIA...
# 4. What that user can do (it should only be sending email)
aws --profile <profile> iam list-attached-user-policies --user-name <UserName>
aws --profile <profile> iam list-user-policies --user-name <UserName>
Step 4 matters: an SMTP user with more than send permission is a key worth rotating and narrowing.
Bugs Worth Fixing in Scripts Like This
Reading the script closely turned up bugs that weren't causing visible harm but are common in versions of this script. The follow-up version fixes three and deliberately leaves one:
| Problem | Effect | Outcome |
|---|---|---|
| Fine-grained password policy carries over | Every user processed after someone with a fine-grained policy gets that policy's maximum age | Fixed |
| Log never rotated | One ever-growing log nobody reads | Fixed |
| First-run log file name contains the date with slashes and colons | Not a valid file name | Fixed: that line now goes to the normal log |
.Trim("SMTP:") | Trim removes a set of characters, not a prefix, so it can eat letters from the address | Left: it only runs for users with no email address, and the domain filter now skips them first. Use -replace '^SMTP:', '' if you keep that path |
The fine-grained policy bug is the one to check in your own copy. The script sets the maximum age once, before the loop, then overwrites the same variable inside it:
# Before: overwrites the shared value, never resets it
$PasswordPol = (Get-ADUserResultantPasswordPolicy $user)
if ($null -ne ($PasswordPol)) { $maxPasswordAge = ($PasswordPol).MaxPasswordAge }
$expireson = $passwordsetdate + $maxPasswordAge
# After: a per-user value, reset for every user
$userMaxPasswordAge = $maxPasswordAge
$PasswordPol = (Get-ADUserResultantPasswordPolicy $user)
if ($null -ne ($PasswordPol)) { $userMaxPasswordAge = ($PasswordPol).MaxPasswordAge }
$expireson = $passwordsetdate + $userMaxPasswordAge
Tested against dummy user data, a user processed after a fine-grained policy user came out at 79 days to expiry with the fix, and 19 days with the original: a reminder sixty days early, or a password expiring with no reminder at all, depending on which way the policies differ. It only bites if fine-grained policies are in use, which is exactly when nobody is watching for it.
Log rotation, placed straight after the folder check:
# If Log.txt is over 10 MB, move it to LogArchive with a timestamp, keep the newest 5
$LogFile = $DirPath + "\" + "Log.txt"
If ((Test-Path $LogFile) -and ((Get-Item $LogFile).Length -gt 10MB))
{
$LogArchive = $DirPath + "\" + "LogArchive"
New-Item -ItemType Directory $LogArchive -Force | Out-Null
Move-Item $LogFile ($LogArchive + "\" + "Log_" + (Get-Date -Format "yyyyMMdd-HHmmss") + ".txt")
Get-ChildItem $LogArchive -Filter "Log_*.txt" | Sort-Object Name -Descending |
Select-Object -Skip 5 | Remove-Item
}
The timestamped names sort correctly as text, so "newest five" needs no date parsing. The same dummy-data run moved an oversized test log into the archive. Error lines still lack timestamps; that one is still open.
Who the Task Runs As, and Who Can Change It
The task runs as SYSTEM. It works, but sending a few emails needs nothing like that much access: read users from the directory, write to its own folder, talk to SES.
The sharper risk is the folder, not the account. Anyone who can edit the script can run code as SYSTEM on that server. On Windows, new folders created directly under C:\ inherit Modify for Authenticated Users by default, so a scripts folder made there may be writable by anyone who can sign in to the server. Check it:
# Read-only
icacls C:\Scripts
icacls C:\Scripts\PasswordExpiry
Only Administrators and SYSTEM should have Full (F) or Modify (M). If Authenticated Users or Users have M, W or F, lock it down, after adding any other account whose scheduled tasks use scripts in that folder:
# Changes permissions: Administrators and SYSTEM only, inherited below
icacls C:\Scripts /inheritance:r /grant:r "Administrators:(OI)(CI)F" "SYSTEM:(OI)(CI)F"
icacls C:\Scripts /remove:g "Authenticated Users" "Users"
icacls C:\Scripts\PasswordExpiry
Then the account itself:
| Option | For | Against |
|---|---|---|
| Keep SYSTEM | No change; no password to manage | Full control of the server if the script or folder is changed; hard to justify to an auditor |
| Dedicated service account | Least privilege; runs show under a named account | A password to manage, set not to expire; the credential file and task need redoing if it is reset |
| Group managed service account | No password to manage | Can't sign in interactively, so creating the DPAPI credential file needs another method; more work for little gain here |
The recommendation to the client: lock the folder down now, and move the task to a dedicated, non-admin service account as a separate change.
- Create the account in Entra ID, so it synchronises into the managed domain, with a long random password kept in the password manager, set not to expire:
Update-MgUser -UserId <account> -PasswordPolicies DisablePasswordExpiration. - Give it Modify on the script's own folder only. No admin rights.
- Recreate the credential file while signed in as that account (here
runasworks, unlike for SYSTEM). - Change the task to run as the account, "Run whether user is logged on or not". Task Scheduler normally grants Log on as a batch job when you save; if the task won't start, check that right.
- Run the live test, check the log, and update the runbook.
It shouldn't need any extra directory rights: as SYSTEM, the task already reads the managed domain as the server's computer account, which isn't an admin either.
The Bigger Question: Should These Passwords Expire?
Fixing the reminders made it obvious that the reminders only exist because passwords expire. Current guidance has moved away from that:
- NIST's digital identity guidelines (SP 800-63B, revision 4): verifiers "SHALL NOT require subscribers to change passwords periodically", but "SHALL force a change if there is evidence that the authenticator has been compromised" (NIST).
- Microsoft: "Microsoft's latest guidance discourages password expiration policies for cloud-only accounts. The recommended setting is for passwords to never expire." Forced changes lead to predictable passwords; length, banned-password lists, MFA and risk-based sign-in do more (Microsoft Learn).
That doesn't mean switch it off tomorrow. Expiry is often still written into an organisation's own security policy, and removing it is only safe with the replacements in place. For this client, the questions now on the table are:
- Is periodic expiry still required by the client's own policy or by a customer contract, or is it habit?
- Are the compensating controls in place: MFA for everyone, banned-password protection, risk-based sign-in, and a forced change when a password is known to be exposed?
- If expiry stays, should reminders come from something more robust than a scheduled script on one server, run as SYSTEM, with a credential only that server can read?
The reminder email itself is part of the same conversation. It listed the rules of an older policy: at least 8 characters, a mix of upper case, lower case, numbers and symbols, and no reuse of the last 10 passwords. But the links in the email send people to Entra ID to change their password, so Entra's rules are the ones that apply, not the domain policy the text was written from. And the advice has moved on: Microsoft now recommends length (a 14-character minimum) and banned-password checks over character-mix rules. In the published script the guidance is a setting at the top, written along those lines, so it can be kept in step with whatever the client decides.
The reminder fix stands either way. But the more useful outcome of the day was the second conversation: whether the system that needed fixing should exist in its current form at all.
Download the Script
The updated script, with every change in this note, is available to download: PasswordExpiryReminder.ps1.
- It is an inherited script, adapted over the years from widely shared community examples; the original author is not known to us, and the header says so.
- Domains, sender, folder and support address are placeholders (
contoso.com,fabrikam.com,adatum.com). Replace them before use. - The password guidance in the email is a setting near the top. Make it describe the rules where your users actually change their password.
- Test it with a copy limited to your own account, as above, before it emails anyone else. Provided as is.
What Is Documented, Observed, or Inferred
First-hand, 19 November 2026: guests receiving reminders; the Graph checks; no #EXT# in Domain Services; the filter change and its testing; each credential error and its cause; the module clash and the -NoProfile fix; the script bugs, found by reading the code.
From vendor documentation: Domain Services one-way synchronisation including guests; DPAPI scoping of Export-Clixml; SES SMTP credentials derived from IAM keys; get-access-key-info; the NIST and Microsoft password guidance quoted above.
Tested on dummy data, not yet live: the fine-grained policy fix (79 days with the fix, 19 without), log rotation and the log name fix, in an updated script ready to deploy.
Not yet checked: whether the scripts folder really is writable by ordinary users (the default ACL makes it likely, which is why it is the first check); the cloud-only guest's email domain; the SES user's permissions.
Not yet done: timestamps on error lines, the service account, and the decision on password expiry, which belongs to the client.
Closing Thoughts
The tempting fix would have worked for the guests and silently broken it for some of the staff. Checking the data first turned a guess into a rule that can't misfire. And a small ticket is often the cheapest way into a bigger conversation: here, whether passwords should expire at all.
← All guides