[玩转系统] 使用 PowerShell 在 SharePoint Online 中的租户之间复制文档库
作者:精品下载站 日期:2024-12-14 16:00:51 浏览:12 分类:玩电脑
使用 PowerShell 在 SharePoint Online 中的租户之间复制文档库
要求:将包含文件和文件夹的文档库从一个 SharePoint Online 租户复制到另一个租户。
如何跨租户复制 SharePoint Online 文档库?
有许多付费的第 3 方工具,如 ShareGate、Metalogix 等,可以有效地完成此迁移,并且我们可以使用 PowerShell(有限制)来完成此迁移。此导出文档库。
请注意,此 PowerShell 方法存在限制,例如此脚本不复制:
- 版本历史
- 权限
- 工作流程
- 文档库设置
- 有限的元数据等
根据给定的参数,导出脚本会下载单个文档库及其文件和文件夹,或者从源站点下载所有库及其元数据字段值“创建者”、“创建者”、“修改者”和“修改者”到本地磁盘。然后,您可以使用导入脚本将文档库上传到目标站点。
使用 PowerShell 在 SharePoint Online 中导出文档库
根据您的环境在 #regionParameters 部分中设置参数并运行脚本。这将复制所有文件和文件夹并将元数据提取到本地磁盘。
#Function to Extract Metadata of a File to CSV File
Function Extract-PnPFileMetadata([Microsoft.SharePoint.Client.File]$SPFile)
{
Try {
#Calculate URLs
$FileLibraryRelativeURL = $SPFile.ServerRelativeURL.Replace($global:Library.RootFolder.ServerRelativeURL,[string]::Empty)
#Calculate Absolute URL
If($global:Web.ServerRelativeUrl -eq "/")
{
$FileAbsoluteURL= $("{0}{1}" -f $global:Web.Url, $SPFile.ServerRelativeUrl)
}
Else
{
$FileAbsoluteURL= $("{0}{1}" -f $global:Web.Url.Replace($global:Web.ServerRelativeUrl,[string]::Empty), $SPFile.ServerRelativeUrl)
}
#Get Autor, Editor of the file
Get-PnPProperty -ClientObject $SPFile -Property Author, ModifiedBy
#Extract the Metadata of the file
$Metadata = New-Object PSObject
$Metadata | Add-Member -MemberType NoteProperty -name "FileName" -value $SPFile.Name
$Metadata | Add-Member -MemberType NoteProperty -name "ParentLibrary" -value $global:Library.Title
$Metadata | Add-Member -MemberType NoteProperty -name "FileAbsoluteURL" -value $FileAbsoluteURL
$Metadata | Add-Member -MemberType NoteProperty -name "FileLibraryRelativeURL" -value $FileLibraryRelativeURL
$Metadata | Add-Member -MemberType NoteProperty -Name "CreatedBy" -value $SPFile.Author.LoginName
$Metadata | Add-Member -MemberType NoteProperty -name "ModifiedBy" -value $SPFile.ModifiedBy.LoginName
$Metadata | Add-Member -MemberType NoteProperty -name "CreatedOn" -value $SPFile.TimeCreated
$Metadata | Add-Member -MemberType NoteProperty -name "ModifiedOn" -value $SPFile.TimeLastModified
#Send the Metadata to CSV File
$Metadata | Export-Csv $global:MetadataFile -NoTypeInformation -Append
Write-host -f Green "`t`tMetadata Extracted from the File:"$SPFile.ServerRelativeURL
}
Catch {
write-host -f Red "Error Getting Metadata:" $_.Exception.Message
}
}
#Function to Download a Document Library from SharePoint Online site
Function Export-PnPLibrary()
{
param
(
[Parameter(Mandatory=$true)] [string]$LibraryName
)
Try {
Write-host "Exporting Library:"$LibraryName -f Yellow
#Get the Library
$global:Library = Get-PnPList -Identity $LibraryName -Includes RootFolder
#Create a Local Folder for Document Library, if it doesn't exist
$LocalFolder = $global:DownloadPath +"\" +$global:Library.RootFolder.Name
If (!(Test-Path -Path $LocalFolder)) {
New-Item -ItemType Directory -Path $LocalFolder | Out-Null
}
Write-host -f Yellow "`tEnsured Folder for Document Library '$LocalFolder'"
#Get all Items from the Library - with progress bar
$global:counter = 0
$LibraryItems = Get-PnPListItem -List $LibraryName -PageSize 500 -Fields ID,FieldValues -ScriptBlock { Param($items) $global:counter += $items.Count; Write-Progress -PercentComplete `
($global:Counter / ($global:Library.ItemCount) * 100) -Activity "Getting Items from Library:" -Status "Processing Items $global:Counter to $($global:Library.ItemCount)";}
Write-Progress -Activity "Completed Retrieving Folders from Library $LibraryName" -Completed
#Get all Subfolders of the library
$SubFolders = $LibraryItems | Where {$_.FileSystemObjectType -eq "Folder" -and $_.FieldValues.FileLeafRef -ne "Forms"}
$SubFolders | ForEach-Object {
#Ensure All Folders in the Local Path
$LocalFolder = $global:DownloadPath + ($_.FieldValues.FileRef.Substring($global:Web.ServerRelativeUrl.Length)) -replace "/","\"
#Create Local Folder, if it doesn't exist
If (!(Test-Path -Path $LocalFolder)) {
New-Item -ItemType Directory -Path $LocalFolder | Out-Null
}
Write-host -f Yellow "`tEnsured Folder '$LocalFolder'"
}
#Get all Files from the folder
$FilesColl = $LibraryItems | Where {$_.FileSystemObjectType -eq "File"}
$global:Filess = $FilesColl
#Iterate through each file and download
$FilesColl | ForEach-Object {
Try {
$FileDownloadPath = ($global:DownloadPath + ($_.FieldValues.FileRef.Substring($global:Web.ServerRelativeUrl.Length)) -replace "/","\").Replace($_.FieldValues.FileLeafRef,[string]::Empty)
Get-PnPFile -Url $_.FieldValues.FileRef -Path $FileDownloadPath -FileName $_.FieldValues.FileLeafRef -AsFile -Force -ErrorAction Stop
Write-host -f Green "`tDownloaded File from '$($_.FieldValues.FileRef)'"
#Get the Metadata of the File
$File = Get-PnPProperty -ClientObject $_ -Property File
Extract-PnPFileMetadata -SPFile $File
}
Catch {
write-host -f Red "`tError Downloading File from '$($_.FieldValues.FileRef)' : "$_.Exception.Message
}
}
}
Catch {
write-host -f Red "`tError:" $_.Exception.Message
}
}
#Function to export all libraries in a SharePoint Site
Function Export-PnPLibraries()
{
Try {
#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")
#Filter Document Libraries to Scan
$LibraryCollection = Get-PnPList | Where {$_.BaseType -eq "DocumentLibrary" -and $_.Hidden -eq $false -and $SystemLists -notcontains $_.Title -and $_.ItemCount -gt 0}
#Loop through each document library
ForEach($Library in $LibraryCollection)
{
#Call the function to download the document library
Export-PnPLibrary -LibraryName $Library.Title
}
}
Catch {
Write-host -f Red "Error Downloading Libraries:" $_.Exception.Message
}
}
#region Parameters
$SourceSiteURL = "https://crescent.sharepoint.com/sites/ops"
$LibraryName = "Branding"
$global:DownloadPath= "C:\Temp\Migration"
#endregion Parameters
#Connect to SharePoint Online
Connect-PnPOnline $SourceSiteURL -Interactive
$global:Web = Get-PnPWeb
$global:MetadataFile = "$global:DownloadPath\Metadata.csv"
#Delete any existing files and folders in the download location
If (Test-Path $global:DownloadPath) {Get-ChildItem -Path $global:DownloadPath -Recurse| ForEach-object {Remove-item -Recurse -path $_.FullName }}
#Call the function to download a library
Export-PnPLibrary -LibraryName $LibraryName
#To Export all libraries, use:
#Export-PnPLibraries
将文档库导入到 SharePoint Online
导出后,您可以使用以下 PowerShell 脚本将文档库导入到不同的租户。只需确保上述脚本中的“Metadata.csv”文件中的用户 ID 有效即可。如果需要,您可以替换 ID 以匹配目标租户。
#Function to Ensure SharePoint Online User
Function Ensure-PnPUser([string]$UserID)
{
Try {
#Try to Get the User
$User = Get-PnPUser -Identity $UserID
If($User -eq $null) {
$User = New-PnPUser -LoginName $UserID
}
#Return the User Object
$User
}
Catch {
write-host -f Red "`t`t`tError Resolving User $UserID :" $_.Exception.Message
Return $Null
}
}
#Function to Set the Metadata of a Document
Function SetPnP-DocumentMetadata()
{
param
(
[Parameter(Mandatory=$true)] [Microsoft.SharePoint.Client.File] $File,
[Parameter(Mandatory=$true)] [Microsoft.SharePoint.Client.List] $TargetLibrary
)
Try {
#Calculate the Library Relative URL of the File
$TargetFolder = Get-PnPProperty -ClientObject $TargetLibrary -Property RootFolder
$FileLibraryRelativeURL = $File.ServerRelativeUrl.Replace($TargetLibrary.RootFolder.ServerRelativeUrl,[string]::Empty)
$FileItem = Get-PnPProperty -ClientObject $File -Property ListItemAllFields
#Import Metadata CSV File
$MetadataFile = Import-Csv -LiteralPath $global:MetadataFile
#Get the Metadata of the File
$Metadata = $MetadataFile | Where-Object {($_.ParentLibrary -eq ($TargetLibrary.Title)) -and $_.FileLibraryRelativeURL -eq $FileLibraryRelativeURL}
If($Metadata)
{
Write-host -f Yellow "`t`tUpdating Metadata for File '$($File.ServerRelativeURL)'"
#Get 'Created By' and 'Modified By' Users
$FileMetadata = @{}
$Author = Ensure-PnPUser -UserID $Metadata.CreatedBy
$Editor = Ensure-PnPUser -UserID $Metadata.ModifiedBy
$FileMetadata.add("Created",[DateTime]$Metadata.CreatedOn)
$FileMetadata.add("Modified",[DateTime]$Metadata.ModifiedOn)
If($Author -ne $Null)
{
$FileMetadata.add("Author", $Author.LoginName)
}
If($Editor -ne $Null)
{
$FileMetadata.add("Editor", $Editor.LoginName)
}
#Update document properties
Set-PnPListItem -List $TargetLibrary -Identity $FileItem.Id -Values $FileMetadata | Out-Null
Write-host -f Green "`t`t`tMetadata has been Updated Successfully!"
}
}
Catch {
write-host -f Red "`t`t`tError updating Metadata of the Document:"$_.Exception.Message
}
}
#Function to Import all Files and Folders from Local Folder to SharePoint Online
Function ImportPnP-Library()
{
param
(
[Parameter(Mandatory=$true)] [string] $SourceLibraryPath,
[Parameter(Mandatory=$true)] [Microsoft.SharePoint.Client.List] $TargetLibrary
)
Try {
#Get the Target Folder to Upload
$TargetFolder = Get-PnPProperty -ClientObject $TargetLibrary -Property RootFolder
$TargetFolderSiteRelativeURL = $TargetFolder.ServerRelativeURL.Replace($global:Web.ServerRelativeUrl+"/",[string]::Empty)
Get-ChildItem $SourceLibraryPath -Recurse | ForEach-Object {
$TargetFolderRelativeURL = $TargetFolderSiteRelativeURL+$_.FullName.Replace($SourceLibraryPath,[string]::Empty).Replace("\","/")
#write-host $TargetFolderRelativeURL
If ($_.PSIsContainer -eq $True) #If its a Folder, ensure it!
{
Write-host -f Yellow "`t`tEnsuring Folder '$TargetFolderRelativeURL'"
#Ensure Folder
Resolve-PnPFolder -SiteRelativePath $TargetFolderRelativeURL | Out-Null
}
Else #Its a File, Upload it!
{
#Calculate the Parent Folder for File
$TargetFolderURL = (Split-Path $TargetFolderRelativeURL -Parent).Replace("\","/")
$SourceFilePath = $_.FullName
Write-host -f Yellow "`t`tUploading File '$_' to Folder:"$TargetFolderURL
$File = Add-PnPFile -Path $SourceFilePath -Folder $TargetFolderURL
Write-host "`t`t`tFile Uploaded Successfully!" -ForegroundColor Green
#Update Metadata of the File
SetPnP-DocumentMetadata -File $File -TargetLibrary $TargetLibrary
}
}
}
Catch {
write-host -f Red "`t`t`tError Importing Library:" $_.Exception.Message
}
}
#Function to Ensure a SharePoint Online document library
Function EnsurePnP-DocumentLibrary()
{
param
(
[Parameter(Mandatory=$true)] [string] $LibraryName
)
Try {
Write-host -f Yellow "`nEnsuring Library '$LibraryName'"
#Check if the Library exist already
$List = Get-PnPList | Where {$_.Title -eq $LibraryName}
If($List -eq $Null)
{
#Create Document Library
$List = New-PnPList -Title $LibraryName -Template DocumentLibrary -OnQuickLaunch
write-host -f Green "`tNew Document Library '$LibraryName' has been created!"
}
Else
{
#Get the Library
$List = Get-PnPList -Identity $LibraryName
Write-Host -f Magenta "`tA Document Library '$LibraryName' Already exist!"
}
Return $List
}
Catch {
write-host -f Red "`tError Creating Document Library!" $_.Exception.Message
}
}
#Main Function
Function Import-PnPLibraries()
{
Try {
#Get Top Level Folders from the Source as "Document Libraries"
$SourceLibraries = Get-ChildItem -Directory -Path $Global:SourcePath
#Create Document Libraries
ForEach($SourceLibrary in $SourceLibraries)
{
#call the function to Ensure document library
$TargetLibrary = EnsurePnP-DocumentLibrary -LibraryName $SourceLibrary.Name
#Import Files and Folders from the Source to the Destination
ImportPnP-Library -SourceLibraryPath $SourceLibrary.FullName -TargetLibrary $TargetLibrary
}
}
Catch {
write-host -f Red "Error:" $_.Exception.Message
}
}
#region Parameters
$Global:SourcePath = "C:\Temp\Migration"
$Global:TargetSiteURL = "https://national.sharepoint.com/Sites/Operations"
#endregion Parameters
#Connect to SharePoint Online
Connect-PnPOnline $TargetSiteURL -Interactive
$global:Web = Get-PnPWeb
$global:MetadataFile = "$global:SourcePath\Metadata.csv"
#Import a Single Document Library
$Library = EnsurePnP-DocumentLibrary "Mason"
ImportPnP-Library -SourceLibraryPath "$Global:SourcePath\Mason" -TargetLibrary $Library
#Call the function to import all document libraries from the source path
#Import-PnPLibraries
您还可以使用此 PowerShell 脚本备份 SharePoint Online 中的文档库。
相关文章:
- 在 SharePoint Online 中复制文档库:如何在 SharePoint Online 中复制文档库?
- 要使用 PowerShell 将文档库从 SharePoint Online 中的一个网站复制到另一个网站,请使用:SharePoint Online:如何将文档库复制到另一个网站?
猜你还喜欢
- 03-30 [玩转系统] 如何用批处理实现关机,注销,重启和锁定计算机
- 02-14 [系统故障] Win10下报错:该文件没有与之关联的应用来执行该操作
- 01-07 [系统问题] Win10--解决锁屏后会断网的问题
- 01-02 [系统技巧] Windows系统如何关闭防火墙保姆式教程,超详细
- 12-15 [玩转系统] 如何在 Windows 10 和 11 上允许多个 RDP 会话
- 12-15 [玩转系统] 查找 Exchange/Microsoft 365 中不活动(未使用)的通讯组列表
- 12-15 [玩转系统] 如何在 Windows 上安装远程服务器管理工具 (RSAT)
- 12-15 [玩转系统] 如何在 Windows 上重置组策略设置
- 12-15 [玩转系统] 如何获取计算机上的本地管理员列表?
- 12-15 [玩转系统] 在 Visual Studio Code 中连接到 MS SQL Server 数据库
- 12-15 [玩转系统] 如何降级 Windows Server 版本或许可证
- 12-15 [玩转系统] 如何允许非管理员用户在 Windows 中启动/停止服务
取消回复欢迎 你 发表评论:
- 精品推荐!
-
- 最新文章
- 热门文章
- 热评文章
[风口福利] 短视频红利新风口!炬焰创作者平台重磅激励来袭
[韩剧] 宝物岛/宝藏岛/金银岛(2025)【全16集】【朴炯植/悬疑】
[电影] 愤怒的牦牛 (2025) 国语中字 4k
[短剧合集] 2025年05月30日 精选+付费短剧推荐56部
[软件合集] 25年5月30日 精选软件26个
[软件合集] 25年5月29日 精选软件18个
[短剧合集] 2025年05月28日 精选+付费短剧推荐38部
[软件合集] 25年5月28日 精选软件37个
[软件合集] 25年5月27日 精选软件26个
[电影] 毒劫 Havoc(2025)【NF1080P超清】【汤姆·哈迪主演】
[剧集] [央视][笑傲江湖][2001][DVD-RMVB][高清][40集全]李亚鹏、许晴、苗乙乙
[电视剧] 欢乐颂.5部全 (2016-2024)
[电视剧] [突围] [45集全] [WEB-MP4/每集1.5GB] [国语/内嵌中文字幕] [4K-2160P] [无水印]
[影视] 【稀有资源】香港老片 艺坛照妖镜之96应召名册 (1996)
[剧集] 神经风云(2023)(完结).4K
[剧集] [BT] [TVB] [黑夜彩虹(2003)] [全21集] [粤语中字] [TV-RMVB]
[办公模版] office模板合集:包含word、Excel、PowerPoint、Access四类共计2000多个模板
[资源] B站充电视频合集,包含多位重量级up主,全是大佬真金白银买来的~【99GB】
[音乐] 华语流行伤感情经典歌无损音乐合集(700多首)
[影视] 内地绝版高清录像带 [mpg]
[电视剧] [突围] [45集全] [WEB-MP4/每集1.5GB] [国语/内嵌中文字幕] [4K-2160P] [无水印]
[剧集] [央视][笑傲江湖][2001][DVD-RMVB][高清][40集全]李亚鹏、许晴、苗乙乙
[电影] 美国队长4 4K原盘REMUX 杜比视界 内封简繁英双语字幕 49G
[电影] 死神来了(1-6)大合集!
[软件合集] 25年05月13日 精选软件16个
[精品软件] 25年05月15日 精选软件18个
[绝版资源] 南与北 第1-2季 合集 North and South (1985) /美国/豆瓣: 8.8[1080P][中文字幕]
[软件] 25年05月14日 精选软件57个
[短剧] 2025年05月14日 精选+付费短剧推荐39部
[短剧] 2025年05月15日 精选+付费短剧推荐36部
- 最新评论
-
- 热门tag