SPOnlineDocumentLibraryInventory.ps1
|
<#PSScriptInfo .VERSION 1.0.1 .GUID 8a1b8562-39e6-4b36-b892-a8210def1e71 .AUTHOR Chendrayan Venkatesan .COMPANYNAME .COPYRIGHT .TAGS SharePointOnline DocumentLibrary .LICENSEURI .PROJECTURI .ICONURI .EXTERNALMODULEDEPENDENCIES .REQUIREDSCRIPTS .EXTERNALSCRIPTDEPENDENCIES .RELEASENOTES Load required assemblies, tested only on Windows PowwerShell, retrieve file size and folder counts (recursive) .PRIVATEDATA #> <# .DESCRIPTION SharePoint Online Document Library Inventory #> Param( $SiteUrl, $DocumentLibraryName, $SharePointAdmin, $SharePointAdminSecret ) $password = ConvertTo-SecureString "$($SharePointAdminSecret)" -AsPlainText -Force $ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl) $credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($SharePointAdmin, $password) $ctx.Credentials = $credentials $web = $ctx.Web $ctx.Load($web) $ctx.ExecuteQuery() $list = $web.Lists.GetByTitle($DocumentLibraryName) $ctx.Load($list) $ctx.ExecuteQuery() $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL) $Ctx.Credentials = $Credentials $List = $Ctx.Web.Lists.GetByTitle($DocumentLibraryName) $Ctx.Load($List) $Ctx.ExecuteQuery() # Initialize collection and parameters $allItems = New-Object System.Collections.Generic.List[PSCustomObject] $position = $null $batchSize = 5000 $csvPath = ".\$DocumentLibraryName.csv" $totalItems = 0 # Clear CSV if exists if (Test-Path $csvPath) { Remove-Item $csvPath } do { $caml = New-Object Microsoft.SharePoint.Client.CamlQuery $caml.ViewXml = @" <View Scope='RecursiveAll'> <Query> <OrderBy><FieldRef Name='ID' Ascending='TRUE'/></OrderBy> </Query> <ViewFields> <FieldRef Name='ID' /> <FieldRef Name='FileLeafRef' /> <FieldRef Name='FileRef' /> <FieldRef Name='FSObjType' /> <FieldRef Name='File_x0020_Size' /> <FieldRef Name='ItemChildCount' /> <FieldRef Name='FolderChildCount' /> </ViewFields> <RowLimit Paged='TRUE'>$batchSize</RowLimit> </View> "@ if ($position) { $caml.ListItemCollectionPosition = $position } try { $items = $list.GetItems($caml) $ctx.Load($items) $ctx.ExecuteQuery() foreach ($item in $items) { $allItems.Add([PSCustomObject]@{ Name = $item["FileLeafRef"] Path = $item["FileRef"] ItemChildCount = $item["ItemChildCount"] FolderChildCount = $item["FolderChildCount"] Type = if ($item["FSObjType"] -eq 1) { "Folder" } else { "File" } SizeBytes = if ($item["FSObjType"] -eq 0) { $item["File_x0020_Size"] } else { $null } }) } $totalItems += $allItems.Count Write-Host "Processed $totalItems items so far..." $position = $items.ListItemCollectionPosition } catch { Write-Host "Error: $($_.Exception.Message)" -ForegroundColor Red break } } while ($null -ne $position) $allItems | Export-Csv -Path $csvPath -NoTypeInformation $allItems.Clear() |