SharePoint Online: PowerShell kullanarak bir Sitedeki Tüm Belge Envanterini Alın


Gereksinim: PowerShell'i kullanarak SharePoint Çevrimiçi Site Koleksiyonundaki Tüm Belgeleri Listeleyin.

Tüm Belgeleri Almak için SharePoint Çevrimiçi PowerShell

Hiç bir SharePoint Online sitesindeki tüm belgelerin bir listesini almanız gerekti mi? Bu blog yazısında, bir SharePoint Online sitesindeki tüm belgeleri almak için PowerShell'i nasıl kullanabileceğinize bakacağız. Bir sitedeki tüm belgeler hakkında hızlı bir şekilde bilgi toplamanız gerekiyorsa veya tüm belge envanterini bir CSV dosyasına aktarmanız gerekiyorsa bu yararlı olabilir.

SharePoint Online site koleksiyonundaki belge kitaplıklarındaki tüm belgeleri listelemek ve CSV'ye aktarmak için PowerShell'i burada bulabilirsiniz:


#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 Generate Report on all documents in a SharePoint Online Site Collection
Function Get-SPODocumentInventory($SiteURL)
{
    Try {
        #Setup the context
        $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
        $Ctx.Credentials = $Credentials
   
        #Get the web from given URL and its subsites
        $Web = $Ctx.web
        $Ctx.Load($Web)
        $Ctx.Load($Web.Lists)
        $Ctx.Load($web.Webs)
        $Ctx.executeQuery()
 
        #Arry to Skip System Lists and Libraries
        $SystemLists =@("Converted Forms", "Master Page Gallery", "Customized Reports", "Form Templates", "List Template Gallery", "Theme Gallery",
               "Reporting Templates", "Solution Gallery", "Style Library", "Web Part Gallery","Site Assets", "wfpub", "Site Pages", "Images")
     
        Write-host -f Yellow "Processing Site: $SiteURL"
 
        #Filter Document Libraries to Scan 
        $Lists = $Web.Lists | Where {$_.BaseType -eq "DocumentLibrary" -and $_.Hidden -eq $false -and $SystemLists -notcontains $_.Title -and $_.ItemCount -gt 0}
        #Loop through each document library
        Foreach ($List in $Lists)
        {
            #Define CAML Query to Get List Items in batches
            $Query = New-Object Microsoft.SharePoint.Client.CamlQuery
            $Query.ViewXml ="
                <View Scope='RecursiveAll'>
                   <Query>
                      <OrderBy><FieldRef Name='ID' Ascending='TRUE'/></OrderBy>
                   </Query>
                   <RowLimit Paged='TRUE'>$BatchSize</RowLimit>
                </View>"
 
            Write-host -f Cyan "`t Processing Document Library: '$($List.Title)' with $($List.ItemCount) Item(s)"
 
            Do {
                #Get List items
                $ListItems = $List.GetItems($Query) 
                $Ctx.Load($ListItems)
                $Ctx.ExecuteQuery() 

                #Filter Files
                $Files = $ListItems | Where { $_.FileSystemObjectType -eq "File"}

                #Iterate through each file and get data
                $DocumentInventory = @()
                Foreach($Item in $Files)
                {
                    $File = $Item.File
                    $Ctx.Load($File)
                    $Ctx.ExecuteQuery()
 
                    $DocumentData = New-Object PSObject
                    $DocumentData | Add-Member NoteProperty SiteURL($SiteURL)
                    $DocumentData | Add-Member NoteProperty DocLibraryName($List.Title)
                    $DocumentData | Add-Member NoteProperty FileName($File.Name)
                    $DocumentData | Add-Member NoteProperty FileURL($File.ServerRelativeUrl)
                    $DocumentData | Add-Member NoteProperty CreatedBy($Item["Author"].Email)
                    $DocumentData | Add-Member NoteProperty CreatedOn($File.TimeCreated)
                    $DocumentData | Add-Member NoteProperty ModifiedBy($Item["Editor"].Email)
                    $DocumentData | Add-Member NoteProperty LastModifiedOn($File.TimeLastModified)
                    $DocumentData | Add-Member NoteProperty Size-KB([math]::Round($File.Length/1KB))
                       
                    #Add the result to an Array
                    $DocumentInventory += $DocumentData
                }
                #Export the result to CSV file
                $DocumentInventory | Export-CSV $ReportOutput -NoTypeInformation -Append
                $Query.ListItemCollectionPosition = $ListItems.ListItemCollectionPosition
            } While($Query.ListItemCollectionPosition -ne $null)
        }
          
        #Iterate through each subsite of the current web and call the function recursively
        ForEach ($Subweb in $Web.Webs)
        {
            #Call the function recursively to process all subsites underneaththe current web
            Get-SPODocumentInventory($Subweb.url)
        }
    }
    Catch {
        write-host -f Red "Error Generating Document Inventory!" $_.Exception.Message
    }
}
  
#Config Parameters
$SiteCollURL="https://crescent.sharepoint.com/sites/marketing"
$ReportOutput="C:\temp\DocInventory.csv"
$BatchSize = 500

#Setup Credentials to connect
$Cred= Get-Credential
$Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)
  
#Delete the Output Report, if exists
if (Test-Path $ReportOutput) { Remove-Item $ReportOutput }
  
#Call the function 
Get-SPODocumentInventory $SiteCollURL

Komut dosyasındaki site koleksiyonu URL'sini ve rapor çıktı yolunu değiştirin ve şunu çalıştırın:

Bu, PowerShell kullanarak SharePoint Online sitesindeki tüm belgelerin ayrıntılı bir raporunu alır. Tüm belgeleri listelemek için PowerShell'in sonucu aşağıdadır:

Site koleksiyonunun tamamı yerine yalnızca tek bir belge kitaplığında tüm belgeleri listelemeniz gerekiyorsa şunu kullanın: SharePoint Online'daki Kitaplıktaki Tüm Belgeleri Listelemek için PowerShell

PnP PowerShell, Tüm Belge Envanterini SharePoint Çevrimiçi Sitesinden Alacak

Site yapısında manuel olarak gezinmeden, belirli bir SharePoint Online sitesindeki tüm belgeleri hızlı bir şekilde toplamanın bir yolunu mu arıyorsunuz? Elbette, size PnP PowerShell kullanarak bir sitedeki tüm belge envanterini almak için PowerShell'i nasıl kullanacağınızı göstereyim!

Belirli bir site koleksiyonunun tüm belge kitaplıklarındaki tüm dosyaları bir CSV dosyasına almanın PnP PowerShell yolu:


#Parameters
$SiteURL = "https://crescent.SharePoint.com/sites/Marketing"
$CSVPath = "C:\Temp\DocumentInventory.csv"
$global:DocumentInventory = @()
$Pagesize = 2000
 
#Function to scan and collect Document Inventory
Function Get-DocumentInventory
{
     [cmdletbinding()]
    param([parameter(Mandatory = $true, ValueFromPipeline = $true)] $Web)
   
    Write-host "Getting Documents Inventory from Site '$($Web.URL)'" -f Yellow
    Connect-PnPOnline -Url $Web.URL -Interactive

    #Calculate the URL of the tenant
    If($Web.ServerRelativeUrl -eq "/")
    {
        $TenantURL = $Web.Url
    }
    Else
    {
        $TenantURL = $Web.Url.Replace($Web.ServerRelativeUrl,'')
    }
 
    #Exclude certain libraries
    $ExcludedLists = @("Form Templates", "Preservation Hold Library","Site Assets", "Pages", "Site Pages", "Images",
                            "Site Collection Documents", "Site Collection Images","Style Library") 
                               
    #Get All Document Libraries from the Web
    Get-PnPList -PipelineVariable List | Where-Object {$_.BaseType -eq "DocumentLibrary" -and $_.Hidden -eq $false -and $_.Title -notin $ExcludedLists -and $_.ItemCount -gt 0} | ForEach-Object {
        #Get Items from List   
        $global:counter = 0;
        $ListItems = Get-PnPListItem -List $_ -PageSize $Pagesize -Fields Author, Created, File_x0020_Type,File_x0020_Size -ScriptBlock `
                 { Param($items) $global:counter += $items.Count; Write-Progress -PercentComplete ($global:Counter / ($_.ItemCount) * 100) -Activity "Getting Documents from '$($_.Title)'" -Status "Processing Items $global:Counter to $($_.ItemCount)";} | Where {$_.FileSystemObjectType -eq "File"}
        Write-Progress -Activity "Completed Retrieving Documents from Library $($List.Title)" -Completed
     
            #Get Root folder of the List
            $Folder = Get-PnPProperty -ClientObject $_ -Property RootFolder
 
            #Iterate through each document and collect data           
            ForEach($ListItem in $ListItems)
            {  
                #Collect document data
                $global:DocumentInventory += New-Object PSObject -Property ([ordered]@{
                    SiteName  = $Web.Title
                    SiteURL  = $Web.URL
                    LibraryName = $List.Title
                    ParentFolder = $Folder.ServerRelativeURL
                    FileName = $ListItem.FieldValues.FileLeafRef
                    FileType = $ListItem.FieldValues.File_x0020_Type
                    FileSize = [math]::Round($ListItem.FieldValues.File_x0020_Size/1KB)
                    AbsoluteURL = "$TenantURL$($ListItem.FieldValues.FileRef)"
                    CreatedBy = $ListItem.FieldValues.Author.Email
                    CreatedAt = $ListItem.FieldValues.Created
                    ModifiedBy = $ListItem.FieldValues.Editor.Email
                    ModifiedAt = $ListItem.FieldValues.Modified
                })
            }
        }
}
  
#Connect to Site collection
Connect-PnPOnline -Url $SiteURL -Interactive
    
#Call the Function for Webs
Get-PnPSubWeb -Recurse -IncludeRootWeb | ForEach-Object { Get-DocumentInventory $_ }
   
#Export Documents Inventory to CSV
$Global:DocumentInventory | Export-Csv $CSVPath -NoTypeInformation
Write-host "Documents Inventory Report has been Exported to '$CSVPath'" -f Green

İşte SharePoint On-Premises'ın SharePoint belge kitaplığındaki tüm belgeleri almasına yönelik başka bir gönderi: PowerShell kullanarak SharePoint'teki Tüm Belge Envanterini Alma

İlgili makaleler