If you want to get the storage details of files and folder (top level) on a specific document library use the below pnp script
Make sure the SharePoint PnP module is installed and the PnP app module is Registered in the Tenant.(To register application refer https://pnp.github.io/powershell/articles/registerapplication.html)
# Parameters
$SiteURL = "https://yourdomain.sharepoint.com/sites/sitename" #addyour site URL
$ListName = "Shared Documents" #add document library name
$ReportOutput = "C:\Temp\kbFileSizeRpt.csv" #add output path
# Array to store results
$Results = @()
# Connect to the SharePoint site
connect-pnponline -Url $SiteURL -ClientId ad895741-ecd8-46de-b683-d2aa12271431 -Interactive
# Get all items (files and folders) from the document library
$ListItems = Get-PnPListItem -List $ListName -PageSize 500
# Hashtable to store folder sizes by path
$FoldersSize = @{}
# Function to add size to the parent folders
function Add-SizeToParentFolders {
param (
[string]$Path,
[int]$Size
)
while ($Path -ne $null -and $Path -ne "") {
if ($FoldersSize.ContainsKey($Path)) {
$FoldersSize[$Path] += $Size
}
else {
$FoldersSize[$Path] = $Size
}
$Path = [System.IO.Path]::GetDirectoryName($Path)
}
}
# Iterate over each item (files and folders)
foreach ($Item in $ListItems) {
if ($Item.FileSystemObjectType -eq "File") {
# File - Get the file size in bytes and its folder path
$FileSizeBytes = $Item.FieldValues.File_x0020_Size
$FileRef = $Item.FieldValues.FileRef
$FolderPath = [System.IO.Path]::GetDirectoryName($FileRef) # Get the folder path
# Convert the file size to KB (Divide bytes by 1024)
$FileSizeKB = [math]::round($FileSizeBytes / 1024, 2) # Round to 2 decimal places
# Add file details to results
$Results += New-Object PSObject -Property ([ordered]@{
FileName = $Item.FieldValues.FileLeafRef
RelativeURL = $FileRef
FileSize = $FileSizeKB
TotalFileSize = $FileSizeKB # For files, FileSize = TotalFileSize
ItemType = "File"
})
# Add file size to the corresponding folder's total size (in bytes for now)
Add-SizeToParentFolders -Path $FolderPath -Size $FileSizeBytes
}
}
# Add folder details to results (folder size is already accumulated in bytes)
foreach ($Folder in $FoldersSize.Keys) {
# Convert the accumulated folder size to KB (Divide bytes by 1024)
$FolderSizeKB = [math]::round($FoldersSize[$Folder] / 1024, 2) # Round to 2 decimal places
$Results += New-Object PSObject -Property ([ordered]@{
FileName = [System.IO.Path]::GetFileName($Folder)
RelativeURL = $Folder
FileSize = 0 # Folders have no direct file size
TotalFileSize = $FolderSizeKB # Folder size based on files inside it, in KB
ItemType = "Folder"
})
}
# Export the results to a CSV file
$Results | Export-Csv -Path $ReportOutput -NoTypeInformation
Write-Host "File Size Report Exported to CSV Successfully!"
OutPut
The filesize and foldersize in the output will be in KB