SharePoint Online: How to Publish a File using PowerShell?
Requirement: Publish a Document in SharePoint Online
How to Publish a File in SharePoint Online?
When you enable minor versions (or drafts) in SharePoint Online, changes to any document aren’t available to users with read-only permissions until it’s published. Published documents become major versions such as 1.0. Here is how to publish a file in SharePoint Online:
- Navigate to the document library where your file is located.
- Right-click on the document to publish >> In the context menu, choose More >> and then click on Publish.
- Enter a comment in the Comments box and click on OK.
It publishes a major version, and others can view the file now!
PowerShell to Publish a Document in SharePoint Online
Here is the PowerShell you needed to publish a file from SharePoint Online:
#Load SharePoint CSOM Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
#Set Parameters
$SiteURL="https://Crescent.sharepoint.com/sites/marketing"
$FileRelativeURL ="/Sites/Marketing/Team Documents/Project Proposal.docx"
$Comment="Final Version"
#Get Credentials to connect
$Cred= Get-Credential
Try{
#Setup the context
$Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)
#Get the File to Publish
$File = $Ctx.Web.GetFileByServerRelativeUrl($FileRelativeURL)
$Ctx.Load($File)
$Ctx.ExecuteQuery()
#Publish the File
$File.Publish($Comment)
$Ctx.ExecuteQuery()
Write-Host -f Green $File.Name "has been published successfully!"
}
Catch {
Write-host -f Red "Error:" $_.Exception.Message
}
Similarly, you can unpublish a file using: “$File.Unpublish($Comment)” method. Here is another post for bulk publish SharePoint Online: Publish Multiple Documents using PowerShell
How to Publish a Major Version in SharePoint Online using PnP PowerShell?
To publish a major version for all the documents in a SharePoint Online document library in one go, use this PowerShell script:
#Parameters
$SiteURL = "https://crescent.sharepoint.com/sites/marketing"
$ListName = "Branding"
#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -Interactive
#Get all files from the document library
$ListItems = Get-PnPListItem -List $ListName -PageSize 2000 | Where { $_.FileSystemObjectType -eq "File" }
#Iterate through each file
ForEach ($Item in $ListItems)
{
#Get the File from List Item
$File = Get-PnPProperty -ClientObject $Item -Property File
#Check if file draft (Minor version)
If($File.CheckOutType -eq "None" -and $File.MinorVersion)
{
$File.Publish("Major version Published by Script")
$File.Update()
Invoke-PnPQuery
Write-host -f Green "Published file at '$($File.ServerRelativeUrl)'"
}
}