PowerShell SharePoint files count is not accurate

Occasional Contributor

I'm trying to write a powershell script that count all the files inside the main SharePoint folder but some reason my count is not accurate so I'll be really appreciated if I can get any help or suggestion on what might be the reason/

So right now I have "General" folder in my SharePoint Site and it has a ton of file and also nested subfolders. I'm try to count all the files including the files that is located inside the nested subfolders.

```
$SiteURL = "https://comapny.sharepoint.com/sites/Office365Sandbox/"
$searchfor = "sites/Office365Sandbox/Shared Documents/General"
$folderpath = "Shared Documents/General"

$CSVFile = "C:\FileCount\FolderStats.csv"

#Connect to SharePoint Online
Connect-PnPOnline $SiteURL -useWebLogin

#Get the list
$List = Get-PnPList -Identity $folderpath | Where-Object {$_.Title -eq 'Documents'}
#Get Folders from the Library - with progress bar

$global:counter = 0
$FolderItems = Get-PnPListItem -List $folderpath -PageSize 500 -Fields FileLeafRef -ScriptBlock { Param($items) $global:counter += $items.Count; Write-Progress -PercentComplete `
($global:Counter / ($List.ItemCount) * 100) -Activity "Getting Items from List:" -Status "Processing Items $global:Counter to $($List.ItemCount)";} | Where {$_.FileSystemObjectType -eq "Folder"}
Write-Progress -Activity "Completed Retrieving Folders from List $ListName" -Completed

$fieldvalues = $FolderItems.Fieldvalues

$result = @()
foreach ($field in $fieldvalues) {
$obj = New-object psobject -property $field
$result += $obj.fileref
}

$final = $result | where-object { $_ -match $searchfor }

$item = New-Object psobject -Property @{
FolderName = Split-Path -Path $searchfor -Leaf
URL = $searchfor
filesfoldercount = $final.count
}

$item
$item | Export-Csv -Path $CSVFile -NoTypeInformation
```

0 Replies