Automate the Removal of Expired Sharing Links in SharePoint with PowerShell
Sharing is a great feature for collaboration. However, depending on how items, files, or folders are shared, a sharing link might be created or unique permissions on these items are created.
It is possible to set an expiration date on sharing links in SharePoint and OneDrive. For more details, please refer to How to set an expiration date on sharing links in SharePoint and OneDrive. Microsoft introduced the capability to set an expiry date for all types of sharing links: “Anyone”, company-wide (aka. “People in your organization”), and specific users (“People you choose”).
However, when sharing links expire, they are not automatically removed. Additionally, the default expiry time can only be set for anonymous links from the SharePoint Admin Center.
For governance, it is a good practice to include in training materials to encourage end users to set an expiry time and choose the appropriate role for sharing links.
The script will help remove expired sharing links and links created older than a certain time,i.e. 30 days passed to the the parameter
Sample script to remove expired sharing links and sharing links created older than x days
Prerequisites
- PnP PowerShell module needs to be installed
- At least site owner role to the SharePoint site
The script retrieves items and files with unique permissions. It uses the REST API instead of Microsoft Graph to find the creation date of the sharing links. This is because Microsoft Graph does not provide the creation date of sharing links. Based on the expiration date or the specified number of days, the script determines whether the links need to be deleted. It generates a CSV report detailing the sharing links and whether they have been deleted.
Conclusion
Currently, there is no default expiry time for “people you choose” or “people in your organization” links, and expired links are not automatically deleted. Using this script can help clean up your environment by removing expired or older sharing links, thereby enhancing security and governance.
Adapt the script to the needs , e.g. to crawl through multiple sites.
References
How to set an Expiration Date on sharing links in SharePoint and OneDrive