当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] SharePoint Online:PowerShell 列出文档库中的所有文件

作者:精品下载站 日期:2024-12-14 21:09:40 浏览:16 分类:玩电脑

SharePoint Online:PowerShell 列出文档库中的所有文件


要求:使用 PowerShell 列出 SharePoint Online 文档库中的所有文档。

[玩转系统] SharePoint Online:PowerShell 列出文档库中的所有文件

SharePoint Online:使用 PowerShell 获取文档库中的文件列表

有时您可能需要获取 SharePoint Online 文档库中所有文档的列表。如果您需要创建库中所有文件的报告,只想概述库中存储的数据量,或者需要移动或删除库中的所有/部分文件,这会很有帮助。在这篇文章中,我们将介绍如何检索 SharePoint Online 文档库中所有文档的列表。然后,您可以将结果导出为 CSV 格式,以便更轻松地处理它们,因为报告包含文件扩展名、修改日期、作者等数据点。

您还可以使用“导出到 Excel”功能从 SharePoint Online 文档库获取所有文件和文件夹的列表! SharePoint Online:使用 PowerShell 获取文档库清单

以下是列出所有文档的 SharePoint Online PowerShell:


#Load SharePoint CSOM Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
 
#Function to get all files of a folder
Function Get-AllFilesFromFolder([Microsoft.SharePoint.Client.Folder]$Folder)
{
    #Get All Files of the Folder
    $Ctx =  $Folder.Context
    $Ctx.load($Folder.files)
    $Ctx.ExecuteQuery()
 
    #Get all files in Folder
    ForEach ($File in $Folder.files)
    {
        #Get the File Name or do something
        Write-host -f Green $File.Name
    }
         
    #Recursively Call the function to get files of all folders
    $Ctx.load($Folder.Folders)
    $Ctx.ExecuteQuery()
 
    #Exclude "Forms" system folder and iterate through each folder
    ForEach($SubFolder in $Folder.Folders | Where {$_.Name -ne "Forms"})
    {
        Get-AllFilesFromFolder -Folder $SubFolder
    }
}
 
#powershell list all documents in sharepoint online library
Function Get-SPODocumentLibraryFiles()
{
    param
    (
        [Parameter(Mandatory=$true)] [string] $SiteURL,
        [Parameter(Mandatory=$true)] [string] $LibraryName,
        [Parameter(Mandatory=$true)] [System.Management.Automation.PSCredential] $Credential
    )
    Try {
     
        #Setup the context
        $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
        $Ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.UserName,$Cred.Password)
 
        #Get the Library and Its Root Folder
        $Library=$Ctx.web.Lists.GetByTitle($LibraryName)
        $Ctx.Load($Library)
        $Ctx.Load($Library.RootFolder)
        $Ctx.ExecuteQuery()
 
        #Call the function to get Files of the Root Folder
        Get-AllFilesFromFolder -Folder $Library.RootFolder 
     }
    Catch {
        write-host -f Red "Error:" $_.Exception.Message
    }
}
#Config Parameters
$SiteURL= "https://crescent.sharepoint.com/Sites/marketing"
$LibraryName="Documents"

#Get Credentials to connect
$Cred = Get-Credential
 
#Call the function to Get All Files from a document library
Get-SPODocumentLibraryFiles -SiteURL $SiteURL -LibraryName $LibraryName -Credential $Cred

此 PowerShell 获取 SharePoint Online 文档库中的文件列表。虽然上述脚本对于包含

PowerShell 列出 SharePoint Online 中的所有文档

以下是用于 SharePoint Online 的 PowerShell,用于获取文档库中的文件列表:


#Load SharePoint CSOM Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
     
#Config Parameters
$SiteURL= "https://crescent.sharepoint.com/sites/marketing"
$LibraryName = "Shared Documents"
$CSVPath = "C:\Temp\DocumentsInventory.csv"
 
#Get Credentials to connect
$Cred = Get-Credential
 
Try {
    #Setup the context
    $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
    $Ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.UserName,$Cred.Password)
     
    #Get the Web and List
    $Web = $Ctx.Web
    $Ctx.Load($Web)
    $List = $Web.Lists.GetByTitle($LibraryName)
    $Ctx.Load($List)
    $Ctx.ExecuteQuery()

    #Prepare the query
    $Query = New-Object Microsoft.SharePoint.Client.CamlQuery
    $Query.ViewXml = "@
    <View Scope='RecursiveAll'>
        <Query>
            <OrderBy><FieldRef Name='ID' Ascending='TRUE'/></OrderBy>
        </Query>
        <RowLimit Paged='TRUE'>2000</RowLimit>
    </View>"
 
    $Counter=1
    $DataCollection = @()
    #Batch Process items
    Do {
        #powershell sharepoint online list all documents
        $ListItems = $List.GetItems($Query) 
        $Ctx.Load($ListItems)
        $Ctx.ExecuteQuery()
        $Query.ListItemCollectionPosition = $ListItems.ListItemCollectionPosition

        #Iterate through each document in the library
        ForEach($ListItem in $ListItems| Where {$_.FileSystemObjectType -eq "File"})
        {
            #Display a Progress bar
            Write-Progress -Activity "Scanning Files in the Library" -Status "Collection file's Inventory '$($Item.FieldValues.FileRef)' ($Counter of $($List.ItemCount))" -PercentComplete (($Counter / $List.ItemCount) * 100)

            #Collect data        
            $DataCollection += New-Object PSObject -Property ([Ordered] @{
                FileName    = $ListItem.FieldValues["FileLeafRef"]
                RelativeURL = $ListItem.FieldValues["FileRef"]
                CreatedBy   = $ListItem.FieldValues["Created_x0020_By"]
                CreatedOn   = $ListItem.FieldValues["Created"]
                ModifiedBy  = $ListItem.FieldValues["Modified_x0020_By"]
                ModifiedOn  = $ListItem.FieldValues["Modified"]
                FileSize    = $ListItem.FieldValues["File_x0020_Size"]
            })
            $Counter++
        }
    }While($Query.ListItemCollectionPosition -ne $Null)

    #Export Documents data to CSV
    $DataCollection | Export-Csv -Path $CSVPath -Force -NoTypeInformation
    Write-host -f Green "Documents Data Exported to CSV!"
}
Catch {
    write-host -f Red "Error:" $_.Exception.Message
}

此 PowerShell 列出所有文件并将数据导出到 CSV 报告!

用于 SharePoint Online 的 PnP PowerShell 列出所有文档 库存

使用 PnP PowerShell cmdlet Get-PnPListItem 获取给定文档库中的所有文档,以及每个文件的文件名和服务器相对路径。


#Set Variables
$SiteURL= "https://crescent.sharepoint.com/sites/Marketing"
$ListName="Documents"
 
#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -Interactive

#Get All Files from the document library - In batches of 500
$ListItems = Get-PnPListItem -List $ListName -PageSize 500 | Where {$_.FileSystemObjectType -eq "File"}
 
#Loop through all documents
$DocumentsData=@()
ForEach($Item in $ListItems)
{
    #Collect Documents Data
    $DocumentsData += New-Object PSObject -Property @{
    FileName = $Item.FieldValues['FileLeafRef']
    FileURL = $Item.FieldValues['FileRef']
    }
}
#sharepoint online get all files in document library powershell
$DocumentsData

从 SharePoint Online 文档库获取所有文档清单并导出到 CSV

让我们添加一些进度条以使其具有交互性,并从 SharePoint Online 文档库获取所有文档清单列表并将其导出到 CSV 文件:


#Parameters
$SiteURL = "https://crescent.sharepoint.com/sites/mexico"
$ListName= "Documents"
$ReportOutput = "C:\Temp\mex-DocInventory.csv"
$Pagesize = 500
  
#Connect to SharePoint Online site
Connect-PnPOnline $SiteURL -Interactive

#Delete the Output report file if exists
If (Test-Path $ReportOutput) { Remove-Item $ReportOutput}

#Array to store results
$Results = @()
  
#Get all Documents from the document library
$List  = Get-PnPList -Identity $ListName
$global:counter = 0;
$ListItems = Get-PnPListItem -List $ListName -PageSize $Pagesize -Fields Author, Editor, Created, File_x0020_Type -ScriptBlock `
        { Param($items) $global:counter += $items.Count; Write-Progress -PercentComplete ($global:Counter / ($List.ItemCount) * 100) -Activity `
             "Getting Documents from Library '$($List.Title)'" -Status "Getting Documents data $global:Counter of $($List.ItemCount)";} | Where {$_.FileSystemObjectType -eq "File"}
 
$ItemCounter = 0
#Iterate through each item
Foreach ($Item in $ListItems)
{
        $Results += New-Object PSObject -Property ([ordered]@{
            Name              = $Item["FileLeafRef"]
            Type              = $Item.FileSystemObjectType
            FileType          = $Item["File_x0020_Type"]
            RelativeURL       = $Item["FileRef"]
            CreatedByEmail    = $Item["Author"].Email
            CreatedOn         = $Item["Created"]
            Modified          = $Item["Modified"]
            ModifiedByEmail   = $Item["Editor"].Email
        })
    $ItemCounter++
    Write-Progress -PercentComplete ($ItemCounter / ($List.ItemCount) * 100) -Activity "Exporting data from Documents $ItemCounter of $($List.ItemCount)" -Status "Exporting Data from Document '$($Item['FileLeafRef'])"         
}
 
#Export the results to CSV
$Results | Export-Csv -Path $ReportOutput -NoTypeInformation
  
Write-host "Document Library Inventory Exported to CSV Successfully!"

随着文档库中文件数量的增加,保存它们的清单变得越来越困难。为了解决这一挑战,您可以使用 PowerShell 检索文档库中所有文件的列表。在本指南中,我们向您展示了如何使用 PowerShell 获取 SharePoint Online 文档库中的文件列表。

若要获取网站集中所有文档库中的文档清单,请使用:SharePoint Online:使用 PowerShell 的网站文档清单(库、文件夹、子文件夹和文件)报告

经常问的问题:

如何在 PowerShell 中从 SharePoint Online 列表获取项目?

若要从列表中获取所有项目,请使用:$List.GetItems([Microsoft.SharePoint.Client.CamlQuery]::CreateAllItemsQuery())
详细信息:PowerShell 从 SharePoint Online 中的列表中获取所有项目

如何使用 PowerShell 获取 SharePoint 中的文档库列表?

要使用 PowerShell 获取 SharePoint Online 网站中的所有文档库,请使用:Get-PnPList | Where-Object {$_.BaseType -eq “DocumentLibrary”}
详细信息:PowerShell 列出 SharePoint Online 中的所有文档库

如何从 SharePoint Online 网站获取所有文档?

若要从 SharePoint Online 网站获取所有文档清单,您必须循环访问网站中的每个文档库并使用 PowerShell 检索文件。
详细信息:使用 PowerShell 从 SharePoint Online 网站获取所有文档清单

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯