'How to count specific folder items in SharePoint site using PowerShell

I have onprem SharePoint site and I wanted to count all the items total number for a specific folder under "Shared Documents" List so I would be really appreciated if I can get any suggestion or help on how to modify this powershell CSOM script.

I found this example script online and I'm not sure how to modify it to get the total item count for one folder instead of every folder.

So basically I have "Jon" Folder under "Shared Documents" List and I want to count from only that folder.

I need to use CSOM method because there is issue with connecting with pnpmodule in my tenant that's why.

#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 Get-SPOListItemCount{
    [CmdletBinding()]
    [OutputType([int])]
    Param
    (
        [Parameter(Mandatory=$true, HelpMessage="The URL of the site that contains the list or library", Position=0)] [string]$WebUrl,
        [Parameter(Mandatory=$true, HelpMessage="The Title of the list or library", Position=1)] [string]$ListName
    )
 
    Begin{

        #Setup context to connect
        $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($WebUrl)
        $Ctx.Credentials =  New-Object System.Net.NetworkCredential("username", "password")

    }
    Process{
        try{
            #Get the Web
            $Web = $Ctx.Web
            #Get the List
            $List = $web.Lists.GetByTitle($ListName)
            $Ctx.Load($List)
            $Ctx.ExecuteQuery()
            #sharepoint online count items in list
            Return $List.ItemCount
        }
        catch{
            Write-Host -ForegroundColor Red $_.Exception.Message
            return 0
        }
 
    }
    End{
        $Ctx.Dispose()
    }
}
     
#Call the function to get item count
Get-SPOListItemCount -WebUrl "https://share.sp.com/sites/Campaign" -ListName "Shared Documents"


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source