The ticket said "links expire after 30 days, please make it 55." It sounded like a single tenant setting. It wasn't. The 30-day limit the team was blaming had never applied to a single one of their shares, and the setting they wanted doesn't exist for the kind of link they actually use. What fixed it was a small Power Automate flow, but the useful part of this note is how we found out what to build, and the things that were only visible after go-live.
The one idea worth keeping: a sharing link is not a share date. SharePoint reuses links, so if you want access to end N days after someone was given it, you have to read each person's own invite date.
01Prove the cause before you build
The user's explanation was wrong. The tenant settings and 90 days of audit log said so in ten minutes.
Two read-only checks decided everything. First, the tenant's sharing settings (Get-SPOTenant):
| Setting | Value | What it actually means |
|---|---|---|
| RequireAnonymousLinksExpireInDays | 30 | Anyone links expire at 30 days. Nothing else does. |
| ExternalUserExpirationRequired | False | Guest access never expires; the day count next to it is ignored |
| DefaultSharingLinkType | Direct | Shares default to Specific people |
| EnableAzureADB2BIntegration | False | Yet every share still created an Entra guest at share time |
Then 90 days of Search-UnifiedAuditLog -RecordType SharePointSharingOperation for the people who share:
- 0 AnonymousLinkCreated. The 30-day limit had never touched a single share.
- About 300 SecureLinkCreated and about 900 AddedToSecureLink. People were added to existing links three times as often as new links were made. Remember this; it's the whole design.
- Every link update was a permission change. None set an expiry date.
We also chased one red herring. About 4,800 files had been recycled in those 90 days, which looked like a cause. Matching shared files against deletions showed only 5 of 245 shared files deleted, all 45+ days after sharing. That was normal housekeeping. Whatever the reviewers had run into, it wasn't a tenant expiry. The real request was simpler and still valid: make access end on a known date, automatically.
02What Microsoft 365 can and can't expire
There is an admin expiry for Anyone links. There is none for Specific people links. The nearest thing expires the wrong object.
| Option | Why not (or why yes) |
|---|---|
| Raise the tenant link expiry to 55 | Only affects Anyone links, which this team never used. The client also wanted Anyone kept at 30. |
| Sharer types a date on every link | Works, but 50+ cases a month, and one forgotten date means a reviewer with access forever |
| Site guest expiration | Expires the guest, not the share. A reviewer on three cases loses all three at once, on a clock that started at first access. Not retroactive; every extension is a manual owner step. |
| Azure runbook + app registration | Viable, but certificates, admin consent and app-only retesting of every SharePoint call. Kept for later. |
| Daily Power Automate flow, per person | Chosen Standard connectors only, matches the ask exactly, every removal logged |
Mental model
A library where each visitor's card stops working 55 days after the librarian handed it over. The librarian never has to remember. A helper walks round every morning at six, checks every card, takes back the ones that are too old, and leaves a note for the office saying whose cards were taken back.
03Three designs, one survivor
Each version was killed by something real SharePoint did in testing.
- One clock per case folder. Use the folder's created date. Dead quickly: a folder is created days before it's shared, and people often share a single file, not the folder.
- One clock per link. Read each link's Created date, revoke links older than 55 days. Simple, and wrong. When you share a file with a second reviewer, SharePoint usually adds them to the existing link. The second reviewer inherits the first reviewer's date and loses access early. That's the 900 AddedToSecureLink events from section 01.
- One clock per person. Each link carries an Invitations list with every member's own invitedOn. Remove only the people past 55 days; revoke the whole link only when everyone on it has expired.
And then there's the share that has no date at all. When the sharer types an email and clicks Send instead of Copy link, SharePoint often grants a direct permission on the item rather than a link. GetSharingInformation lists that person under principals, with no invite date anywhere. The only way to age it is to remember when you first saw it, so the flow keeps a small tracker list: item ID, person ID, first seen, last seen.
04How the flow works
One scheduled flow, five SharePoint REST calls, one report. Nothing for the sharer to do.
Everything that touches sharing goes through Send an HTTP request to SharePoint, a standard connector action that calls the REST API as the connection's account. The normal SharePoint actions can't read link members or remove one person from a link.
| Purpose | Call | Needs |
|---|---|---|
| List items + whether each has its own permissions | GET …/items?$select=Id,FileRef,HasUniqueRoleAssignments&$top=5000 | Read |
| Links, members, invite dates, direct grants | POST …/items(id)/GetSharingInformation?$expand=permissionsInformation | Site Owner |
| Revoke a whole link | POST …/items(id)/UnshareLink | Site Owner |
| Remove one person from a link | POST _api/web/sitegroups/getbyname('SharingLinks.<item>.Flexible.<shareId>')/users/removebyid(id) | Site Collection Admin |
| Remove a direct (Send) grant | POST …/roleassignments/getbyprincipalid(id) + X-HTTP-Method: DELETE | Site Owner |
The fourth call is the one to understand. Behind every Specific-people link, SharePoint keeps a hidden group named SharingLinks.<item id>.Flexible.<link id>. The people on the link are that group's members. Remove a member and that person is off the link while it keeps working for everyone else.
Three details that each cost a test cycle:
- GetSharingInformation only works as POST, and needs Accept and Content-Type: application/json;odata=nometadata. Without them SharePoint answers in Atom XML and every filter downstream silently reads nothing.
- Every shared item comes back with two placeholder links: ShareId all zeros, inactive, no date. Filter them out (IsActive and non-zero ShareId) or the flow tries to revoke ghosts.
- A Uri with two leading spaces fails with 401 Unauthorized, not a parse error. The error body shows %20%20_api if you look for it.
The report is built from a RunLog array of small records (action, file, folder, person, shared date, days, who still has access), turned into table rows with a Select and wrapped in one Compose of table-based, inline-styled HTML, because Outlook desktop ignores most modern CSS. It's sent from a shared mailbox the service account has Send As on, so it reads "Expert Access Alerts" rather than a service account name, and only on days something changed. A DryRun switch makes the flow do everything except remove, with "would revoke" wording and a yellow banner, which is how every test ran.
The one-line model
When the platform has no expiry for a kind of access, don't expire the object that's easiest to see (the folder, the link, the guest). Expire the thing the requirement is actually about, here each person's grant, and read that date from where SharePoint really stores it.
05The 403 that testing hides
Everything passed under my account. Under the service account, per-person removal failed.
Site Owner can't edit the hidden SharingLinks groups
The flow was built and tested under the engineer account that created the site, and site creators are Site Collection Admins automatically. Moved to a dedicated service account with Site Owner (Full Control), the "remove one person from a link" call returned 403 Access denied. Revoking a whole link and deleting direct grants still worked, so only the partial case broke. The fix is Set-SPOUser -IsSiteCollectionAdmin $true for the service account on that one site only. If you test as the site creator, you'll never see this until production.
The service account itself is deliberately boring: no directory roles, password in the vault and set not to expire (a password change breaks every connection), MFA registered, one licence with only Exchange, SharePoint and Power Automate switched on, Site Collection Admin on one site, Send As on one mailbox, and its own mail forwarded to the alerts DL because flow-failure notices go to owners. One gotcha: assigning the licence seconds after creating the account left the Exchange plan in Error for a while, because Exchange couldn't see the user yet. Wait a minute or two before licensing.
06Day one: the 5,000-item wall
The first scheduled run succeeded. It had also only looked at two-thirds of the library.
The morning after go-live the flow ran green. Its first REST call had returned exactly 5,000 items, all from a single case, with an odata.nextLink at the top of the reply. The library held 7,528. The team's first case included imaging discs: a DICOM viewer is thousands of small files, and one case had pushed the library past 5,000 within hours.
SharePoint returns at most 5,000 items per REST request and hands you the address of the next page. A flow that makes one call never sees the rest. When we fixed it, page two held all four of the team's first real reviewer shares. Without the fix, none of them would ever have expired, and nothing would have looked wrong.
The fix is a Do until loop that follows odata.nextLink until it's empty, filtering each page down to shared items as it goes so the working set stays small:
NextUrl = _api/web/lists/getbytitle('Documents')/items?$select=Id,FileRef,FileDirRef,HasUniqueRoleAssignments&$top=5000
Do until = empty(variables('NextUrl'))
Get page = GET @{variables('NextUrl')}
Merged = union(variables('SharedItems'), body('Page_shared'))
NextUrl = if(empty(body('Get_page')?['odata.nextLink']), '',
substring(body('Get_page')?['odata.nextLink'],
indexOf(body('Get_page')?['odata.nextLink'], '_api/')))
Two small things in there: Set variable can't reference itself, hence the Merged Compose, and the next-page address comes back absolute, so it's cut back to _api/… to match the relative form the SharePoint action expects. Verified on the next run: two pages, 5,000 + 2,528, matching the item count in Site contents, and all four shares found.
A green run means the flow checked everything.
A capped REST reply is a success. Compare what the flow read against the library count in Site contents after the first real day of use, not just after testing on an empty site.
Site Owner is enough to manage sharing on a site.
Owners can revoke whole links, but removing one person from a link edits a system-owned group and needs Site Collection Admin.
07Testing without waiting 55 days
You can't backdate a sharing link. You can move the line instead.
| Technique | Set the cutoff to | Use it for |
|---|---|---|
| Short cutoff | addMinutes(utcNow(), -2) | Anything shared more than two minutes ago counts as expired |
| Pinned cutoff | A fixed UTC time between two shares | Per-person tests: the earlier reviewer expires, the later one doesn't, however long you take |
| Backdate the tracker | Leave it at N days; edit FirstSeen | Send shares at the real production setting |
| Dry run | DryRun = true | Everything except the removal, with "would" wording |
Every path was run dry then live: link one and two folders deep, two reviewers on one link with both expired and with one expired, a direct Send share, placeholder links, and site members checked after every removal. Remember the timezone: SharePoint stores UTC, so a pinned cutoff typed in local time is hours off.
08The setup scripts
The flow is built by hand in the designer. Everything around it is scripted, interactive and reusable.
| File | What it does | Changes anything? |
|---|---|---|
| 01-Get-SharingBaseline.ps1 | Tenant sharing settings + audit-log summary: Anyone vs Specific-people links, people added to existing links, manual expiry dates | No |
| 02-New-AutomationServiceAccount.ps1 | Role-less account, password shown once, licence with only the plans you keep, waits for Exchange first | Yes |
| 03-Set-ShareExpirySite.ps1 | Anyone links off on the site, Specific people default, guest expiry override off, service account Owner + Site Collection Admin | Yes |
| 04-New-AlertSenderMailbox.ps1 | Hidden shared sender mailbox, Send As, service account mail forwarded to the alerts DL | Yes |
01 and 03 need Windows PowerShell 5.1: the SharePoint Online cmdlets aren't recognised in PowerShell 7. The download also includes the report's HTML template.
⇩ Download the toolkit — 4 scripts + email template (.zip)09Limits worth stating up front
- One site per flow. Keep external sharing on a dedicated site. A whole OneDrive estate needs a different design.
- Send shares can be up to a day late, because their clock starts on the first morning the flow sees them.
- More time for a reviewer means sharing again. That starts a fresh period; nothing to configure.
- The removal is access, not data. Anything a reviewer downloaded stays downloaded. If that matters, it's a labelling and DLP question, not an expiry one.
Sources & further reading
- Manage sharing settings for SharePoint and OneDriveLink expiration is an Anyone-link setting; guest access expiration is separate
Comments
Questions or corrections welcome. Sign in with GitHub to join the thread.