Delete File Version By Version Id in SharePoint using PowerShell

The example in this topic show how to use PowerShell to Delete File Version By Version Id in SharePoint

  • # Provide credentials over here
  • $creds = (New-Object System.Management.Automation.PSCredential "<<UserName>>",(ConvertTo-SecureString "<<Password>>" -AsPlainText -Force))
  •  
  • # Provide URL of the Site over here
  • # If you do not wish to pass credentials hard coded then you can use: -Credentials (Get-Credential). This will prompt to enter credentials
  • Connect-PnPOnline -Url http://MyServer/sites/MySiteCollection -Credentials $creds
  •  
  • # Get Context
  • $clientContext = Get-PnPContext
  •  
  • # -Url: relative path of the file
  • # -AsListItem: Retrieves the file and returns it as a ListItem object
  • $ListItem = Get-PnPFile -Url "/Shared Documents/atest.txt" -AsListItem
  •  
  • # Get the File object
  • $targetFile = $ListItem.File
  •  
  • $clientContext.Load($targetFile)
  •  
  • $clientContext.ExecuteQuery()
  •  
  • # Delete File version using version Id
  • # NOTE: Every Major check In will be incremented by "512" e.g. version 1.0 will have ID = 512, Version 2.0 will have ID = 1024
  • # Every Minor check in will be incremented by "1" e.g. version 0.1 will have ID = 1 , version 0.2 will have ID = 2
  • $targetFile.Versions.DeleteByID(3)
  •  
  • $clientContext.ExecuteQuery()
  •  
  • Disconnect-PnPOnline 

Thank you for reading this article. This code was tested in SharePoint 2013


© 2019 Code SharePoint