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 enabled minor versions (or drafts) in SharePoint Online, all changes to any document isn't available to users with read only permissions, until its Published. Published documents becomes 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.
    publish document in sharepoint online
  • Enter a comment in the Comments box and click on OK.
It publishes a major version and file can be viewed by others now!

PowerShell to Publish a Document in 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
$FileRelativeURL ="/Sites/Marketing/Team Documents/Project Proposal.docx"
$Comment="Final Version"

#Get Credentials to connect
$Cred= Get-Credential

    #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)

    #Publish the File

    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 my 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:
$SiteURL = "" 
$ListName = "Branding"

#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -UseWebLogin
#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")
        Write-host -f Green "Published file at '$($File.ServerRelativeUrl)'"

No comments:

Please Login and comment to get your questions answered!

Powered by Blogger.