cancel
Showing results for 
Search instead for 
Did you mean: 
Reply
mardex
Helper II
Helper II

Flow Deleting old Versions on Sharepoint

Good day,

 

I have to run a flow each day to update datas. When I run them a new Version of the document is always created.

I have around 24 GB of Datas, Each File multiplied by 100. 
So I have 1,4 TB of data and my Storage is full.

 

MY QUESTION: Does anybody know how to delete all old Versions of a File in Sharepoint as it is not possible to set Versions to a lower Number then 100

 

Thanks


BRGDS
Jan Held

2 ACCEPTED SOLUTIONS

Accepted Solutions
mardex
Helper II
Helper II

I mean delete with FLOW!!!! not manually


@mardex wrote:

Good day,

 

I have to run a flow each day to update datas. When I run them a new Version of the document is always created.

I have around 24 GB of Datas, Each File multiplied by 100. 
So I have 1,4 TB of data and my Storage is full.

 

MY QUESTION: Does anybody know how to delete all old Versions of a File in Sharepoint as it is not possible to set Versions to a lower Number then 100

 

Thanks


BRGDS
Jan Held


 

View solution in original post

Hi @mardex,

 

Please refer to the following steps to delete the old versions of each file in the SharePoint library:

 

Step 1: Add Get files(properties only) action to get files in the list.

Step 2: Add Send an HTTP request to SharePoint

Method: GET
Uri: _api/web/GetFolderByServerRelativeUrl('Dynamic content of Folder Path')/Files('Dynamic content of File name with extension')/Versions

Annotation 2019-08-29 150852.pngStep 3: Parse JSON, put the body of the previous action into the Content of Parse JSON action, then click the button "Use sample payload" to generate schema to paste the following schema:

{
"type": "object",
"properties": {
"d": {
"type": "object",
"properties": {
"results": {
"type": "array",
"items": {
"type": "object",
"properties": {
"__metadata": {
"type": "object",
"properties": {
"id": {
"type": "string"
},
"uri": {
"type": "string"
},
"type": {
"type": "string"
}
}
},
"CreatedBy": {
"type": "object",
"properties": {
"__deferred": {
"type": "object",
"properties": {
"uri": {
"type": "string"
}
}
}
}
},
"CheckInComment": {
"type": "string"
},
"Created": {
"type": "string"
},
"ID": {
"type": "integer"
},
"IsCurrentVersion": {
"type": "boolean"
},
"Length": {
"type": "string"
},
"Size": {
"type": "integer"
},
"Url": {
"type": "string"
},
"VersionLabel": {
"type": "string"
}
},
"required": [
"__metadata",
"CreatedBy",
"CheckInComment",
"Created",
"ID",
"IsCurrentVersion",
"Length",
"Size",
"Url",
"VersionLabel"
]
}
}
}
}
}
}

 

Annotation 2019-08-29 151226.png

Step 4: Create the other Send an Http request to SharePoint:

Method: DELETE
Uri: _api/web/GetFolderByServerRelativeUrl('Dynamic content of Folder Path')/Files('Dynamic content of File name with extension')/Versions(ID from the previous action)

Please have a try, I hope it can help you.

 

Best Regards,
Community Support Team _ Lin Tu
If this post helps, then please consider Accept it as the solution to help the other members find it more quickly.

View solution in original post

12 REPLIES 12
mardex
Helper II
Helper II

I mean delete with FLOW!!!! not manually


@mardex wrote:

Good day,

 

I have to run a flow each day to update datas. When I run them a new Version of the document is always created.

I have around 24 GB of Datas, Each File multiplied by 100. 
So I have 1,4 TB of data and my Storage is full.

 

MY QUESTION: Does anybody know how to delete all old Versions of a File in Sharepoint as it is not possible to set Versions to a lower Number then 100

 

Thanks


BRGDS
Jan Held


 

@mardex 

To delete old versions, you'll need to use the SharePoint HTTP action and call a SharePoint web service.  I can't provide the specifics, but that's the route you'll need to go.  Another way to approach this might be to create a new document (based on the old document including metadata) and delete the old one rather than updating the existing documents in your Flow.

If I have answered your question, please mark your post as Solved.
If you like my response, please give it a Thumbs Up.

Scott

thanks, I expected this. So it will be a hell of work for me as a non professional Smiley Sad


@ScottShearer wrote:

@mardex 

To delete old versions, you'll need to use the SharePoint HTTP action and call a SharePoint web service.  I can't provide the specifics, but that's the route you'll need to go.  Another way to approach this might be to create a new document (based on the old document including metadata) and delete the old one rather than updating the existing documents in your Flow.


 

Hi @mardex,

 

Please refer to the following steps to delete the old versions of each file in the SharePoint library:

 

Step 1: Add Get files(properties only) action to get files in the list.

Step 2: Add Send an HTTP request to SharePoint

Method: GET
Uri: _api/web/GetFolderByServerRelativeUrl('Dynamic content of Folder Path')/Files('Dynamic content of File name with extension')/Versions

Annotation 2019-08-29 150852.pngStep 3: Parse JSON, put the body of the previous action into the Content of Parse JSON action, then click the button "Use sample payload" to generate schema to paste the following schema:

{
"type": "object",
"properties": {
"d": {
"type": "object",
"properties": {
"results": {
"type": "array",
"items": {
"type": "object",
"properties": {
"__metadata": {
"type": "object",
"properties": {
"id": {
"type": "string"
},
"uri": {
"type": "string"
},
"type": {
"type": "string"
}
}
},
"CreatedBy": {
"type": "object",
"properties": {
"__deferred": {
"type": "object",
"properties": {
"uri": {
"type": "string"
}
}
}
}
},
"CheckInComment": {
"type": "string"
},
"Created": {
"type": "string"
},
"ID": {
"type": "integer"
},
"IsCurrentVersion": {
"type": "boolean"
},
"Length": {
"type": "string"
},
"Size": {
"type": "integer"
},
"Url": {
"type": "string"
},
"VersionLabel": {
"type": "string"
}
},
"required": [
"__metadata",
"CreatedBy",
"CheckInComment",
"Created",
"ID",
"IsCurrentVersion",
"Length",
"Size",
"Url",
"VersionLabel"
]
}
}
}
}
}
}

 

Annotation 2019-08-29 151226.png

Step 4: Create the other Send an Http request to SharePoint:

Method: DELETE
Uri: _api/web/GetFolderByServerRelativeUrl('Dynamic content of Folder Path')/Files('Dynamic content of File name with extension')/Versions(ID from the previous action)

Please have a try, I hope it can help you.

 

Best Regards,
Community Support Team _ Lin Tu
If this post helps, then please consider Accept it as the solution to help the other members find it more quickly.

Hi there,

 

Is it possible to set this up to on-demand remove all of the previous versions in a selected folder only, rather than daily automation for the whole library?

 

I would like to be able to select a project folder within a library once that project is completed, delete all the previous versions, keeping only the final files and then mark all files in that folder as read only so that no new versions are created if people then go and look at the files as reference for another project.

 

Many thanks

 

Chris

Many thanks

This is exactly what I am looking for, do you have more details you can provide on this or a video you can point me to on how to create this flow?  When I create the Uri there is no dynamic content to choose from.  It seems some steps are missing.  What trigger do you use?  I tried using scheduled once a week.  Also is there a way to keep say 5 versions?

pityman
Helper III
Helper III

This is what i want to do. but the things is I will exceed the 500 Apply to each limitation as I have a lot of files in a folder + subfolders. is there anyone can help?

Hellcat
New Member

PnP PowerShell should become your fried if it is not already.  There a ton of good resources available to answer you requirements or get you headed in the right direction.  Salaudeen Rajack at https://www.sharepointdiary.com/ is an outstanding resource.  He has been very generous in sharing many PnP scripts to accomplish a task, and all of them can be adjusted to do more or less, or become very granular.

 

Hop over to https://www.sharepointdiary.com/ and search for "delete versions" or Google it.  I've modified the available scripts for date ranges, file types, selection by user, operations on specific folders and more.

 

First thing I did was to set max versions to the minimum of 100 in the SharePoint admin center.  100 is as low as they allow you to go.  It would be fantastic if MS would reduce the number to something more reasonable.

 

Next thing was to delete all version of any image file (JPG, TIFF etc.)  There is a script at https://www.sharepointdiary.com/ to delete all versions.  Just modify it for the file type or file extension you want to delete all versions for.

 

Next verify you users are okay to retain 1, 2, 5, 10 versions of an MS Office file type or extension, then modify and run the available script to delete all but "x" number of versions for that file type.  I got rid of many PPTX, DOCX and XLSX version.  Some of the PPTX and DOCX are huge files.

 

Use use an image size reducing app to shrink your pictures, then go back and delete the picture versions.  Irfanview is a great free tool for shrinking images.

 

Have your users reduce the size their PowerPoint files.  The go back and delete old versions again with PS PnP.

 

Once you have your PS scripts tuned they way you need them, schedule them to run daily/weekly/monthly.

 

SharePoint Flows are good but can be a challenge to get right.  For me, PowerShell scripting and automation is the way to go.  Much more intuitive and flexible.  There isn't too much you cannot accomplish with PS.

 

Oh yeah, keep your Recycle Bin and Secondary Recycle Bin emptied on a schedule.  Yes, there is a PS script for that.

 

I recovered 700+ GB by doing the things listed above, and significantly reduced my personal workload by automating with PS.

I was asked where I found the max versions setting.

 

Document library settings cog in upper-right > Library Settings > More Library settings > Versioning settings.

 

Additional info can be found at SharePoint Online: Set Versioning Limit using PowerShell - SharePoint Diary

Hi I am running into an issue when following this example. When i create a library with a few files for testing it worked. When i revert back to the main task of deleting old versions from a library with subfolders i keep being told file error. Am i missing a trick with a setting when it is for a large library?

Many thanks for you help

Assuming you are trying to delete versions with PowerShell and PnP from a library with more than 5k items...  There is a limit to how many items that can be retrieved at one time.  The -PageSize flag to limit the number of items retrieved per-page to less than the 5000-item limit enforced by SharePoint, which cannot be changed.  I usually limit to 2k items per page, which works 99% of the time.  In rare cases where 2k still causes problems I drop it to 500.

Here is a basic example script that deletes all versions for JPG images, modified within the last 60-days, and edited by a particular user.

DO NOT test this on a production site.

I AM NOT responsible for your deleted data, production or otherwise.

# Much credit for this goes to sharepointdiary.com
# https://www.sharepointdiary.com/2018/05/sharepoint-online-delete-version-history-using-pnp-powershell.html

# This script will delete ALL versions of JPG files and leave the current file.

#Declare Variables
# Change "yourdomain" to your actual O365 domain
# Change "yoursite" to your actual SharePoint site name
$SiteURL = "https://yourdomain.sharepoint.com/sites/yoursite"

# If neccessary change "Documents" to the actual name of your library in your site
# "Documents is created by default unless you changed the name during intial site creation
$ListName="Documents"

# Set number of days to query. You can use this to limit how far back to query.  Helpful for huge libraries years old.
# Or omit it altogether to check every file for versions.  Takes a LONG TIME with 500K+ JPGs.
# If you omit the number of days variable, you must also remove "-and ($_.FieldValues.Last_x0020_Modified.ToString() -gt $AfterDate) `" from the WHERE filter below.
$AfterDate = (Get-date).AddDays(-60).ToString('yyyy-MM-dd')

# Counters used for different tasks
$TotalFiles = 0
$TotalVerDeleted = 0
$CurrentCount = 0
$MatchedJpg = 0
 
# Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -Interactive
 
#Get the Context
$Ctx= Get-PnPContext

# Get the List
# List items are counted for the first progress bar
$List =  Get-PnPList -Identity $ListName
 
# Initialize a counter for the first progress bar
$global:counter = 0;

# Get All Items from the List - Include only 'File' object List Items, with 'jpg' extension, after a specified date, and last Edited by a specific user
# Change "someusernameemail*" to a unique username, of someone that edited the JPGs.
# For example, I compress thousands of JPGs so my email address will be the current Editor and I only look for versions to delete of the files I edited.
# You can always remove the Editor filter to check all JPGs in the library for version to delete.
# Set the -PageSize to avoid query problems if your library has more than 5k items.
# Show progress bar as list items are retrieved 2000 items at a time
$ListItems = Get-PnPListItem `
    -List $ListName `
    -PageSize 2000 `
    -ScriptBlock { `
        Param($items) $global:counter += $items.Count; `
        Write-Progress -Id 0 `
            -Activity "Retrieving $ListName list to check for JPG files edited since $AfterDate." `
            -Status "Retrieved $global:Counter of $($List.ItemCount) Items from the $ListName list." `
            -PercentComplete ($global:Counter / ($List.ItemCount) * 100);} | `
    Where {`
        ($_.FileSystemObjectType -eq "File") `
        -and ($_.Fieldvalues["File_x0020_Type"] -eq "jpg") `
        -and ($_.FieldValues.Last_x0020_Modified.ToString() -gt $AfterDate) `
        -and ($_.FieldValues['Editor'].Email -like "someusernameemail*")}

#Number of JPGs that matched the "where" criteria
$MatchedJpg = $ListItems.Count

ForEach ($Item in $ListItems)
{
    $CurrentCount = $CurrentCount + 1
    
    #Get File Versions
    $File = $Item.File
    $Versions = $File.Versions
    $Ctx.Load($File)
    $Ctx.Load($Versions)
    $Ctx.ExecuteQuery()
    $VersionsCount = $Versions.Count

    Write-Progress -Id 1 -ParentID 0 `
        -Activity "Checking $MatchedJpg files for Versions to delete." `
        -Status "Checking file $CurrentCount of $($ListItems.Count)." `
        -PercentComplete ($CurrentCount / ($ListItems.Count) * 100)
     
    If($VersionsCount -gt 0)
    {      
        #Increment counter for total number of files found with Versions
        $TotalFiles = $TotalFiles + 1

        Write-host -f Cyan "`t $TotalFiles Files with Versions to delete so far."
        Write-host -f White "`t Deleting" $Versions.Count "version(s) of:" $File.Name

        For($i=0; $i -lt $Versions.Count; $i++)
        {
            $TotalVerDeleted = $TotalVerDeleted + 1
                       
            write-host -f Magenta "`t Deleting Version:" $Versions[0].VersionLabel

            $Versions[0].DeleteObject()
        }

        $Ctx.ExecuteQuery()

        Write-Host -f White "`t Deleted" $VersionsCount "Version(s) of:" $File.Name "`n"
    }
}

Write-Host -f Cyan `t "Total Versions deleted:" $TotalVerDeleted

Disconnect-PnPOnline

Rookie move on my part.  Replied to myself. ¯\_(ツ)_/¯ 

Assuming you are trying to delete versions with PowerShell and PnP from a library with more than 5k items...  There is a limit to how many items that can be retrieved at one time.  The -PageSize flag to limit the number of items retrieved per-page to less than the 5000-item limit enforced by SharePoint, which cannot be changed.  I usually limit to 2k items per page, which works 99% of the time.  In rare cases where 2k still causes problems I drop it to 500.

Here is a basic example script that deletes all versions for JPG images, modified within the last 60-days, and edited by a particular user.

DO NOT test this on a production site.

I AM NOT responsible for your deleted data, production or otherwise.

# Much credit for this goes to sharepointdiary.com
# https://www.sharepointdiary.com/2018/05/sharepoint-online-delete-version-history-using-pnp-powershell.html

# This script will delete ALL versions of JPG files and leave the current file.
# DO NOT run it on a production site/library if you are required to retain some number of previous versions for whatever reason.

#Declare Variables
# Change "yourdomain" to your actual O365 domain
# Change "yoursite" to your actual SharePoint site name
$SiteURL = "https://yourdomain.sharepoint.com/sites/yoursite"

# If neccessary change "Documents" to the actual name of your library in your site
# "Documents is created by default unless you changed it during intial site creation
$ListName="Documents"

# Set number of days to query. You can use this to limit how far back to query.  Helpful for huge libraries years old.
# Or omit it altogether to check every file for versions.  Takes a LONG TIME with 500K+ JPGs.
# If you omit the number of days variable, you must also remove "-and ($_.FieldValues.Last_x0020_Modified.ToString() -gt $AfterDate) `" from the WHERE filter below.
$AfterDate = (Get-date).AddDays(-60).ToString('yyyy-MM-dd')

# Counters used for different tasks
$TotalFiles = 0
$TotalVerDeleted = 0
$CurrentCount = 0
$MatchedJpg = 0
 
# Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -Interactive
 
#Get the Context
$Ctx= Get-PnPContext

# Get the List
# List items are counted for the first progress bar
$List =  Get-PnPList -Identity $ListName
 
# Initialize a counter for the first progress bar
$global:counter = 0;

# Get All Items from the List - Include only 'File' object List Items, with 'jpg' extension, after a specified date, and last Edited by a specific user
# Change "someusernameemail*" to a unique username, of someone that edited the JPGs.
# For example, I compress thousands of JPGs so my email address will be the current Editor and I only look for versions to delete of the files I edited.
# You can always remove the Editor filter to check all JPGs in the library for version to delete.
# Set the -PageSize to avoid query problems if your library has more than 5k items.
# Show progress bar as list items are retrieved 2000 items at a time
$ListItems = Get-PnPListItem `
    -List $ListName `
    -PageSize 2000 `
    -ScriptBlock { `
        Param($items) $global:counter += $items.Count; `
        Write-Progress -Id 0 `
            -Activity "Retrieving $ListName list to check for JPG files edited since $AfterDate." `
            -Status "Retrieved $global:Counter of $($List.ItemCount) Items from the $ListName list." `
            -PercentComplete ($global:Counter / ($List.ItemCount) * 100);} | `
    Where {`
        ($_.FileSystemObjectType -eq "File") `
        -and ($_.Fieldvalues["File_x0020_Type"] -eq "jpg") `
        -and ($_.FieldValues.Last_x0020_Modified.ToString() -gt $AfterDate) `
        -and ($_.FieldValues['Editor'].Email -like "someusernameemail*")}

#Number of JPGs that matched the "where" criteria
$MatchedJpg = $ListItems.Count

ForEach ($Item in $ListItems)
{
    $CurrentCount = $CurrentCount + 1
    
    #Get File Versions
    $File = $Item.File
    $Versions = $File.Versions
    $Ctx.Load($File)
    $Ctx.Load($Versions)
    $Ctx.ExecuteQuery()
    $VersionsCount = $Versions.Count

    Write-Progress -Id 1 -ParentID 0 `
        -Activity "Checking $MatchedJpg files for Versions to delete." `
        -Status "Checking file $CurrentCount of $($ListItems.Count)." `
        -PercentComplete ($CurrentCount / ($ListItems.Count) * 100)
     
    If($VersionsCount -gt 0)
    {      
        #Increment counter for total number of files found with Versions
        $TotalFiles = $TotalFiles + 1

        Write-host -f Cyan "`t $TotalFiles Files with Versions to delete so far."
        Write-host -f White "`t Deleting" $Versions.Count "version(s) of:" $File.Name

        For($i=0; $i -lt $Versions.Count; $i++)
        {
            $TotalVerDeleted = $TotalVerDeleted + 1
                       
            write-host -f Magenta "`t Deleting Version:" $Versions[0].VersionLabel

            $Versions[0].DeleteObject()
        }

        $Ctx.ExecuteQuery()

        Write-Host -f White "`t Deleted" $VersionsCount "Version(s) of:" $File.Name "`n"
    }
}

Write-Host -f Cyan `t "Total Versions deleted:" $TotalVerDeleted

Disconnect-PnPOnline

 

Helpful resources

Announcements
Microsoft 365 Conference – December 6-8, 2022

Microsoft 365 Conference – December 6-8, 2022

Join us in Las Vegas to experience community, incredible learning opportunities, and connections that will help grow skills, know-how, and more.

Users online (2,923)