Delete All Versions of a SharePoint File Using PowerShell

There may be instances where you need to remove all previous versions of a file. Well, this is the PowerShell script to do it. This will only work for SharePoint on-premises however.

param(
[string] $UrlToFile
)

$Site = New-Object -Type Microsoft.SharePoint.SPSite -ArgumentList $UrlToFile
$Web = $Site.OpenWeb()
$SPFile = $Web.GetFile($UrlToFile)

Write-Host “Deleting all versions for file $($UrlToFile)…”

# Remove all versions for file…
$SPFile.Versions.DeleteAll()

# Dispose of the web object
$Web.Dispose()

# Dispose of the site object
$Site.Dispose()

Save this off as something rememberable, such as Remove-FileVersions.ps1, and pass it the full URL to the file you wish to remove all versions from, for example:

.\Remove-FileVersions.ps1 “http://mysharepoint.com/sites/foo/Documents/Document_1.docx”

Enjoy!

Advertisement
%d bloggers like this: