SharePoint Online: Check If File Exists in Document Library using PowerShell CSOM

Requirement: Check if a file exists in SharePoint online document library using PowerShell CSOM.
sharepoint online check file exists powershell

PowerShell to check if a file exists in SharePoint online document library:
Lets check if file exists in SharePoint document library with 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"
  
#Function to Check if file exists in given URL
Function Check-FileExists($SiteURL, $FileRelativeURL, $Credentials)
{
    #Setup the context
    $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
    $Ctx.Credentials = $Credentials

    Try {
        #Try to get the File from URL
        $File = $Ctx.web.GetFileByServerRelativeUrl($FileRelativeURL)
        $Ctx.Load($File)
        $Ctx.ExecuteQuery()
        Return $True
    }
    Catch {
        Return $False
    }    
}

#Set Variables for Site URL, List Name and Column Name
$SiteURL= "https://crescent.sharepoint.com/sites/sales/"
$FileRelativeURL="/sites/Sales/TeamDocuments/LegalTemplate.docx"

#Setup Credentials to connect
$Cred = Get-Credential
$Cred = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.UserName,$Cred.Password)

#Call the function to Check Column Exists in given list
$FileExists = Check-FileExists -SiteURL $SiteURL -FileRelativeURL $FileRelativeURL -Credentials $Cred

if($FileExists) {
    write-host "File Exists in the Given URL!" -f Green
    #Proceed with your script
 }
 else {
    write-host "File Doesn't Exists in the given URL!" -f Red
 }
This checks if file exists in SharePoint document library with csom powershell.

PnP PowerShell to Check File Exists in Document Library
Here is how to check file exists in SharePoint library,
#Parameters
$SiteURL = "https://crescent.sharepoint.com/sites/dochub/"
$FileSiteRelativeURL = "/documents/2018/IC Papers.txt"

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

#Check if File exists Already
$FileExists = Get-PnPFile -Url $FileSiteRelativeURL -ErrorAction SilentlyContinue

If($FileExists)
{
    Write-host -f Green "File Exists!"    
}
Else
{
    Write-host -f Yellow "File Doesn't Exists!"
}
SharePoint Online: Check If File Exists in Document Library using PowerShell CSOM SharePoint Online: Check If File Exists in Document Library using PowerShell CSOM Reviewed by Salaudeen Rajack on October 08, 2016 Rating: 5

No comments:

Please Login and comment to get your questions answered!

Powered by Blogger.