Power Automate: How to delete SharePoint Files and Folder
Building a scheduled Flow to delete SharePoint files and folders is essential, especially if you have a Dynamics 365 environment integrated with your SharePoint. After a record has been retained for a certain number of years, you may reach a point where you need to delete it from your system. However, simply deleting the record directly in D365 will not delete the corresponding files on the SharePoint side, which means you will end up with a lot of junk data in your SharePoint.
In this blog, I will show you how to use Power Automate to delete SharePoint files and folders.
Trigger of the Flow:
Select Recurrence trigger. In my example, I’d like to have my flow to run at 5am everyday.
Step 1: Get the all Accounts created on over 10 years
This is just my example; you can modify your trigger as long as you have a list of accounts to be deleted.
Step 2: Get the ‘relativeurl’
The ‘relativeurl’ column is from the Document Location table. We need that column in order to find the correct SharePoint Item.
Step 3: Get Files
Using the OOTB SharePoint action in Flow to get all the files you want to delete; Things to be aware:
- Include Nested Items meaning you are retrieving files from the Subfolder.
- By Default, Get Files action treat Subfolder as a ‘File’, so we use this ODATA query to get the actual files only, not any subfolders.
FSObjtype eq 0
Step 4: Delete File
Use the SharePoint Delete File action to delete the file, using the Identifier column from the Step 3 — Get Files
Step 5: Delete Folder
Unfortunitely, at this time, we still dont have a built in action in Power Automate to delete SharePoint folder, so we have to use the ‘Send an HTTP request to SharePoint’ to delete the folder.
Please note that this step will fail, if your folder contains sub folders.
Now that the SharePoint side of things is all done, you can continue using your flow to delete the target record. Thanks to the cascading rule, the related Document Location record will also get deleted.
Hope this blog helps you.