SharePoint Online: Check If a Folder Exists using PowerShell

Requirement: Check if a folder exists in the SharePoint Online document library.

Check If Folder Exists in SharePoint Online using PowerShell

SharePoint Online: PowerShell to Check If Folder Exists

When Working with SharePoint Online PowerShell scripts, you may need to determine if a folder exists in SharePoint Online before creating a new folder or deleting an existing folder. In this blog post, we’ll show you how to use PowerShell to check if a folder exists in SharePoint Online quickly!

Why Check if a Folder Exists?

Before we dive into the technical details, let’s understand the importance of checking if a folder exists in a SharePoint document library. Here are a few reasons why this check is valuable:

  1. Avoiding Duplicate Folders: When creating new folders programmatically or through user input, it’s essential to ensure that a folder with the same name doesn’t already exist. Checking for the folder’s existence helps prevent duplicates and maintains a clean and organized document library structure.
  2. Conditional Processing: In certain scenarios, you may need to perform specific actions based on whether a folder exists or not. For example, if a folder exists, you might want to upload files to it, whereas if it doesn’t exist, you may want to create the folder first and then proceed with the file upload.
  3. Error Handling: When automating SharePoint processes, error handling is crucial. Checking if a folder exists allows you to gracefully handle situations where the folder doesn’t exist and provide appropriate feedback or take alternative actions.

Now that we understand the importance of checking folder existence, let’s explore the different methods for achieving this using PowerShell.

Here is the PowerShell for SharePoint Online to check if a folder exists:

#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 folder Exists
Function Check-SPOFolderExists()
{
  param
    (
        [Parameter(Mandatory=$true)] [string] $SiteURL,
        [Parameter(Mandatory=$true)] [string] $FolderRelativeURL
    )
    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
        $Web = $Ctx.Web
        $Ctx.Load($Web)
        $Ctx.ExecuteQuery()

        #Check Folder Exists
        Try { 
            $Folder = $Web.GetFolderByServerRelativeUrl($FolderRelativeURL)
            $Ctx.Load($Folder)
            $Ctx.ExecuteQuery() 

            Write-host -f Green "Folder Exists!"
        }
        Catch {
            Write-host -f Yellow "Folder Doesn't Exist!"
        }        
    }
    Catch {
        write-host -f Red "Error Checking Folder Exists!" $_.Exception.Message
    }
}
 
#Set parameter values
$SiteURL="https://crescent.sharepoint.com/"
$FolderRelativeURL="/Shared Documents/2018"

#Call the function 
Check-SPOFolderExists -SiteURL $SiteURL -FolderRelativeURL $FolderRelativeURL 

This PowerShell script connects to SharePoint Online, checks if a specified folder exists in a document library, and provides feedback on the folder’s existence status. You can adjust the $SiteURL and $FolderRelativeURL variables to match your SharePoint Online site and the folder path you want to check.

Alternatively, you can use the other method used in my other article: SharePoint Online: Create a Folder using PowerShell

PnP PowerShell to Check if a folder exists in SharePoint Online

When automating SharePoint provisioning or deployment processes, it’s crucial to verify the existence of certain folders before proceeding with further actions. For example, you may want to check if a specific folder structure is in place before creating new documents or uploading files to ensure data integrity and avoid conflicts.

The PnP PowerShell way to check whether a folder exists or not in the given location goes here: Let’s say, you have a SharePoint Online document library named “Marketing Materials” and you want to check if a folder named “Brochures” exists within it. Here’s how you can use the PowerShell script to accomplish this:

#Parameters
$SiteURL = "https://crescent.sharepoint.com/sites/Operations"
$FolderURL = "/sites/Operations/Marketing Materials/Brochures" #Server Relative URL

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

#Try to Get the Folder 
$Folder = Get-PnPFolder -Url $FolderURL -ErrorAction SilentlyContinue

#sharepoint online powershell To check if folder exists
If($Folder -ne $null)
{
    Write-Host -f Green "Folder exists!"
}
Else
{
    Write-Host -f Yellow "Folder does not exists!"
}

After checking for the folder’s existence, you might want to create it if it does not exist. This can be easily achieved by extending the above scripts with folder creation logic.

Alright, the above two scripts check whether the given folder exists in the specified URL. How about checking if a folder has a specific sub-folder in SharePoint Online?

#Parameters
$SiteURL = "https://crescent.sharepoint.com/sites/Operations"
$ParentFolderURL = "/Shared Documents" #Site Relative URL
$FolderName = "Classified"

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

    #Try to Get the Folder from given parent folder
    $Folder = Get-PnPFolderItem -FolderSiteRelativeUrl $ParentFolderURL -ItemType Folder -ItemName $FolderName

    #Powershell To check if folder exists
    If($Folder -ne $null)
    {
        Write-Host -f Green "Folder exists!"
    }
    Else
    {
        Write-Host -f Yellow "Folder does not exists!"
    }
}
catch {
    write-host "Error: $($_.Exception.Message)" -foregroundcolor Red
}

By running this script, you’ll receive a message indicating whether the “Brochures” folder exists in the “Marketing Materials” library or not.

How to check if a Document Library has a specific Folder or not using PowerShell?

The script below checks if the given document library has a specific folder (at its root level).

#Parameters
$SiteURL = "https://crescent.sharepoint.com/sites/Operations"
$LibraryName = "Documents"
$FolderName = "Classified"

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

    #Try to Get the Folder from document library
    $Folder = Get-PnPFolder -List $ListName | Select -ExpandProperty Name | Where {$_.Name -eq $FolderName}

    # check if folder exists in the document library - ONLY AT ROOT LEVEL
    If($Folder -ne $null)
    {
        Write-Host -f Green "Folder exists!"
    }
    Else
    {
        Write-Host -f Yellow "Folder does not exists!"
    }
}
catch {
    write-host "Error: $($_.Exception.Message)" -foregroundcolor Red
}

The above examples show how to use PowerShell to determine if a folder exists in SharePoint Online. Using these scripts, you can easily verify whether a folder already exists in a document library or list before creating it, or verify that a specific folder has been deleted.

Conclusion

Checking if a folder exists in a SharePoint document library is a common task that can be easily accomplished using PowerShell. In this article, we explored different approaches to check folder existence, including using PnP PowerShell for SharePoint Online and SharePoint Online CSOM. We also discussed real-world examples to illustrate the practical applications of checking folder existence.

What if you want to create a new folder if it doesn’t exist? To create a folder in SharePoint Online using PowerShell, refer: How to create a New Folder in SharePoint Online with PowerShell?

Salaudeen Rajack

Salaudeen Rajack - Information Technology Expert with Two-decades of hands-on experience, specializing in SharePoint, PowerShell, Microsoft 365, and related products. He has held various positions including SharePoint Architect, Administrator, Developer and consultant, has helped many organizations to implement and optimize SharePoint solutions. Known for his deep technical expertise, He's passionate about sharing the knowledge and insights to help others, through the real-world articles!

One thought on “SharePoint Online: Check If a Folder Exists using PowerShell

  • is there a way to use this script to loop through all the list of site URLS that we can input using CSV file?

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *