SharePoint Online: PowerShell to Bulk Check In All Documents

Requirement: Bulk Check in All Documents in SharePoint Online using PowerShell.

How to bulk check in documents in SharePoint Online?

There may be times when you need to bulk check in documents in SharePoint Online. How to check in multiple documents in SharePoint Online? Well, You can check in either a single file or multiple files in a document library by selecting them and choosing “Check in” within a few clicks.

sharepoint online bulk check in powershell

However, We have a huge document library with many documents checked out and want them to check in to make them available to end-users. I tried creating a view that filters all checked-out files, but failed since the list item count is > 5000 (List view threshold issue!)

SharePoint Online: PowerShell to Check in All Documents

Do you need to check in a large number of files at once in SharePoint Online? If so, PowerShell can help. Here is the PowerShell to check in multiple files in the SharePoint Online document library:

#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"
$LibraryName="Shared Documents"
 
Try{
    #Get Credentials to connect
    $Cred= Get-Credential
    $Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)
  
    #Setup the context
    $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
    $Ctx.Credentials = $Credentials
 
    #Get the Web and List
    $Web = $Ctx.Web
    $Ctx.Load($Web)
    $List = $Web.Lists.GetByTitle($LibraryName)
    $Ctx.Load($List)
    $Ctx.ExecuteQuery()
 
    #Prepare the query
    $Query = New-Object Microsoft.SharePoint.Client.CamlQuery
    $Query.ViewXml = "@
    <View Scope='RecursiveAll'>
        <Query>
            <OrderBy><FieldRef Name='ID' Ascending='TRUE'/></OrderBy>
        </Query>
        <RowLimit Paged='TRUE'>2000</RowLimit>
    </View>"
 
    $Counter=1
    #Batch Process items: sharepoint online powershell bulk check in 
    Do {
        $ListItems = $List.GetItems($Query)
        $Ctx.Load($ListItems)
        $Ctx.ExecuteQuery()
 
        $Query.ListItemCollectionPosition = $ListItems.ListItemCollectionPosition
 
        #Get All Checked out files
        ForEach($Item in $ListItems | Where {$_.FileSystemObjectType -eq "File"})
        {
            #Display a Progress bar
            Write-Progress -Activity "Scanning Files in the Library" -Status "Testing if the file is Checked-Out '$($Item.FieldValues.FileRef)' ($Counter of $($List.ItemCount))" -PercentComplete (($Counter / $List.ItemCount) * 100)

            #Get the Checked out File data
            $File = $Ctx.Web.GetFileByServerRelativeUrl($Item["FileRef"])
            $Ctx.Load($File)
            $CheckedOutByUser = $File.CheckedOutByUser
            $Ctx.Load($CheckedOutByUser)
            $Ctx.ExecuteQuery()
 
            If($File.Level -eq "Checkout")
            {
                Write-Host -f Yellow "Found a Checked out File '$($File.Name)' at $($Web.url)$($Item['FileRef']), Checked Out By: $($CheckedOutByUser.LoginName)"

                #Check in the document
                $File.CheckIn("Checked-in By Administrator through PowerShell!", [Microsoft.SharePoint.Client.CheckinType]::MajorCheckIn)      
                $Ctx.ExecuteQuery()
                Write-Host -f Green "File '$($File.Name)' Checked-In Successfully!"
            }
            $Counter++
        }
    }While($Query.ListItemCollectionPosition -ne $Null)
}
Catch {
        write-host -f Red "Error Check In Files!" $_.Exception.Message
}

SharePoint Online: Check in Multiple Files using PowerShell

Let’s scan the entire site collection for checked out files and check in them back using PowerShell.

#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"
 
#PowerShell to Bulk check-in all documents
Function CheckIn-AllDocuments([String]$SiteURL)
{
    Try{
        #Setup the context
        $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
        $Ctx.Credentials = $Credentials

        #Get the Web
        $Web = $Ctx.Web
        $Ctx.Load($Web)
        $Ctx.Load($Web.Webs)
        $Ctx.ExecuteQuery()

        #Get All Lists from the web
        $Lists = $Web.Lists
        $Ctx.Load($Lists)
        $Ctx.ExecuteQuery()
 
        #Prepare the CAML query
        $Query = New-Object Microsoft.SharePoint.Client.CamlQuery
        $Query.ViewXml = "@
        <View Scope='RecursiveAll'>
            <Query>
                <OrderBy><FieldRef Name='ID' Ascending='TRUE'/></OrderBy>
            </Query>
            <RowLimit Paged='TRUE'>2000</RowLimit>
        </View>"

        #Array to hold Checked out files
        $CheckedOutFiles = @()
        Write-host -f Yellow "Processing Web:"$Web.Url
        
        #Iterate through each document library on the web
        ForEach($List in ($Lists | Where-Object {$_.BaseTemplate -eq 101 -and $_.Hidden -eq $False -and $_.ItemCount -gt 0}) )
        {
            Write-host -f Yellow "`t Processing Document Library:"$List.Title

                $Counter=1
                #Batch Process List items 
                Do {
                    $ListItems = $List.GetItems($Query)
                    $Ctx.Load($ListItems)
                    $Ctx.ExecuteQuery()

                    $Query.ListItemCollectionPosition = $ListItems.ListItemCollectionPosition

                    #Get All Checked out files
                    ForEach($Item in $ListItems | Where {$_.FileSystemObjectType -eq "File"})
                    {
                        #Display a Progress bar
                        Write-Progress -Activity "Scanning Files in the Library" -Status "Testing if the file is Checked-Out '$($Item.FieldValues.FileRef)' ($Counter of $($List.ItemCount))" -PercentComplete (($Counter / $List.ItemCount) * 100)

                        Try{
                            #Get the Checked out File data
                            $File = $Web.GetFileByServerRelativeUrl($Item["FileRef"])
                            $Ctx.Load($File)
                            $CheckedOutByUser = $File.CheckedOutByUser
                            $Ctx.Load($CheckedOutByUser)
                            $Ctx.ExecuteQuery()

                            If($File.Level -eq "Checkout")
                            {
                                Write-Host -f Green "`t`t Found a Checked out File '$($File.Name)' at $($Item['FileRef']), Checked Out By: $($CheckedOutByUser.LoginName)"

                                #Check in the document
                                $File.CheckIn("Checked-in By Administrator through PowerShell!", [Microsoft.SharePoint.Client.CheckinType]::MajorCheckIn)      
                                $Ctx.ExecuteQuery()
                                Write-Host -f Green "`t`t File '$($File.Name)' Checked-In Successfully!"
                            }
                        }
                        Catch {
                            write-host -f Red "Error Check In: $($Item['FileRef'])" $_.Exception.Message
                        }
                        $Counter++
                    }
                }While($Query.ListItemCollectionPosition -ne $Null)
        }

        #Iterate through each subsite of the current web and call the function recursively
        ForEach($Subweb in $Web.Webs)
        {
            #Call the function recursively to process all subsites underneath the current web
            CheckIn-AllDocuments -SiteURL $Subweb.URL
        }
    }
    Catch {
        write-host -f Red "Error Bulk Check In Files!" $_.Exception.Message
    }
}

#Config Parameters
$SiteURL="https://crescent.sharepoint.com/Sites/Marketing"
 
#Setup Credentials to connect
$Cred= Get-Credential
$Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)
 
#Call the function: sharepoint online powershell to check in all documents in a Site Collection
CheckIn-AllDocuments -SiteURL $SiteURL

If you need to check in a file in SharePoint Online, use: PowerShell to Check In a Document in SharePoint Online

PnP PowerShell to Check-In All Files in a Document Library

Here is how to use PnP PowerShell to check in all documents in the SharePoint Online document library:

#Parameter
$SiteURL= "https://crescent.sharepoint.com/sites/marketing/"
$ListName = "Documents"

#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -Interactive

#Get All List Items from the List - Filter Files
$ListItems = Get-PnPListItem -List $ListName -PageSize 500 | Where {$_["FileLeafRef"] -like "*.*"}

#Loop through each list item
ForEach ($Item in $ListItems)
{
    Write-host -f Yellow "Testing If file is Checked-Out:"$Item.FieldValues["FileRef"]
    #Get the File from List Item
    $File = Get-PnPProperty -ClientObject $Item -Property File

    If($File.Level -eq "Checkout")
    {
        #Check-In and Approve the File
        Set-PnPFileCheckedIn -Url $File.ServerRelativeUrl -CheckinType MajorCheckIn

        Write-host -f Green "`tFile Checked-In:"$File.ServerRelativeUrl
    }
} 

Salaudeen Rajack

Salaudeen Rajack is a SharePoint Architect with Two decades of SharePoint Experience. He loves sharing his knowledge and experiences with the SharePoint community, through his real-world articles!

12 thoughts on “SharePoint Online: PowerShell to Bulk Check In All Documents

  • I got “File Not Found.” error on some of the files – and found those files were with special characters such as #

    Reply
  • There seem to be a problem with the property “Level” which might no longer exist. I modified the script in that line 18 to check for the property “CheckOutType”. If that one is not equal to “None” the script progresses to change all the check in all those files:

    Before:
    If($File.Level -eq “Checkout”)

    After:
    If($File.CheckOutType -ne “None”)

    Reply
  • This was a life saver! I had to disable MFA temporarily while the script ran. If you ever have time you may want to update to include modern authentication at the beginning if possible.

    Appreciate the script!

    Reply
  • I get this error when i try to run the full scan
    Error Check In Files! Exception calling “ExecuteQuery” with “0” argument(s): “The attempted operation is prohibited because it exceeds the list view threshold.”

    Reply
    • Post has been updated with the CSOM script to handle larger libraries. You can try the PnP PowerShell script as well!

      Reply
      • The PnP script just does the first part which is to test if files are checked but it does not actually check them in. Please help

        Reply
        • Hey there

          I’m facing the same issue here. The PnP script lists all the checked in files, marked in yellow but does not affect the checked out files.

          Can you provide an update?

          Best regards
          David

          Reply
  • Could you please post a version that gets around the “view limit” threshold? I am trying to combine this script with the one you posted here, which lists items 1000 at a time:
    https://www.sharepointdiary.com/2016/12/sharepoint-online-get-all-items-from-large-lists-powershell-csom.html#comment-form

    Reply
  • I am getting the error when trying to check in multiple files in a document library in sharepoint online as below

    Error Check In Files! Exception calling “.ctor” with “2” argument(s): “The ‘username’ argument is invalid.”

    Reply
    • Make sure the username you supply is correct and You are using this script in SharePoint Online (Not on On-premises!)

      Reply

Leave a Reply