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

[玩转系统] SharePoint Online:使用 PowerShell 在文档库之间复制文件

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

SharePoint Online:使用 PowerShell 在文档库之间复制文件


要求:SharePoint Online PowerShell 将文件从一个库复制到另一个库。

如何复制 SharePoint Online 文档库中的文件?

您是否正在寻找在 SharePoint Online 中复制文件的方法?本指南将向您展示如何使用“复制到”功能在站点、文档库或文件夹之间快速轻松地复制文件。我们还将向您展示如何使用 PowerShell 在 SharePoint Online 环境中的位置之间复制文件。

您可以使用现代体验将文件从一个 SharePoint Online 库复制到另一个库。以下是复制 SharePoint Online 文档库中的文件的方法:

  1. 导航到包含要复制的文件的 SharePoint Online 文档库 >> 选择要复制的文件 >> 右键单击并选择“复制到”菜单项。您还可以使用工具栏中的“复制到”按钮。

    [玩转系统] SharePoint Online:使用 PowerShell 在文档库之间复制文件

  2. 将出现一个新窗口,允许您选择要将文件复制到的位置。选择您的文件需要复制到的目标库。您可以选择当前库、当前网站上的任何其他库,甚至任何不同网站集中的库。

    [玩转系统] SharePoint Online:使用 PowerShell 在文档库之间复制文件

  3. 选择库并单击“复制此处”按钮开始复制文件。
  4. 您将在工具栏中看到“正在复制”消息,并且您的文件将立即复制到目标站点上。

    [玩转系统] SharePoint Online:使用 PowerShell 在文档库之间复制文件

相同的过程也适用于移动操作。

在“复制到”或“移动到”页面的“快速访问”下找不到您所在的一侧?那么,您可以使用“添加 OneDrive 快捷方式”将库快捷方式添加到 OneDrive,然后单击“复制到”页面中的“我的文件”来选择该库。

SharePoint Online 中的复制与移动
复制文件时,不会保留创建者、修改者等元数据。此外,复制文件时不会保留版本历史记录。而 Move 保留元数据和版本。

您是否经常发现自己需要将文件从 SharePoint Online 环境复制到其他位置? PowerShell 可以帮助您快速轻松地完成此过程!

SharePoint Online:用于复制文档的 PowerShell

PowerShell 是一个功能强大的工具,可用于自动执行 SharePoint Online 中的任务。让我们看看如何使用 PowerShell 在 SharePoint Online 中复制文件。以下是用于复制 SharePoint Online 文档库中的文件的 PowerShell:


Function Copy-File
{
  param
    (
        [Parameter(Mandatory=$true)] [string] $SiteURL,
        [Parameter(Mandatory=$true)] [string] $SourceFileURL,
        [Parameter(Mandatory=$true)] [string] $TargetFileURL
    )
    Try {
        $Cred= Get-Credential
        $Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)
        #Setup the context
        $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
        $Ctx.Credentials = $Credentials
        #Get the source file
        $SourceFile =$Ctx.Web.GetFileByServerRelativeUrl($SourceFileURL)
        $Ctx.Load($SourceFile)
        $Ctx.ExecuteQuery()
        #Copy File to destination
        $SourceFile.CopyTo($TargetFileURL, $True)
        $Ctx.ExecuteQuery()
        Write-Host "File Copied from '$SourceFileURL' to '$TargetFileURL'" -F Green
       }
    Catch {
        write-host -f Red "Error Copying File!" $_.Exception.Message
    }
}
#Set Parameter values
$SiteURL="https://crescent.sharepoint.com/"
$SourceFileURL="/Project Documents/Active Users.xlsx"
$TargetFileURL="/Project Documents/Active UsersV2.xlsx"
#Call the function 
Copy-File -SiteURL $SiteURL -SourceFileURL $SourceFileURL -TargetFileURL $TargetFileURL 

此方法将给定文档及其元数据字段复制到同一个文档库或同一站点内的不同文档库(除了:创建者和修改者字段 - 显然,这些列应该存在于两个库中)!

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 Copy a File
Function Copy-SPOFile([String]$SiteURL, [String]$SourceFileURL, [String]$TargetFileURL)
{
    Try{
        #Setup the context
        $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
        $Ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)
     
        #Copy the File
        $MoveCopyOpt = New-Object Microsoft.SharePoint.Client.MoveCopyOptions
        $Overwrite = $True
        [Microsoft.SharePoint.Client.MoveCopyUtil]::CopyFile($Ctx, $SourceFileURL, $TargetFileURL, $Overwrite, $MoveCopyOpt)
        $Ctx.ExecuteQuery()
 
        Write-host -f Green "File Copied Successfully!"
    }
    Catch {
    write-host -f Red "Error Copying the File!" $_.Exception.Message
    }
}
 
#Set Config Parameters
$SiteURL="https://Crescent.sharepoint.com/sites/Marketing"
$SourceFileURL="https://Crescent.sharepoint.com/sites/Marketing/Shared Documents/Discloser Asia.doc"
$TargetFileURL="https://Crescent.sharepoint.com/Shared Documents/Discloser Asia.doc"
 
#Get Credentials to connect
$Cred= Get-Credential
 
#Call the function to Copy the File
Copy-SPOFile $SiteURL $SourceFileURL $TargetFileURL

使用 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 Copy-AllFiles
{
  param
    (
        [Parameter(Mandatory=$true)] [string] $SiteURL,
        [Parameter(Mandatory=$true)] [Microsoft.SharePoint.Client.Folder] $SourceFolder,
        [Parameter(Mandatory=$true)] [Microsoft.SharePoint.Client.Folder] $TargetFolder
    )
    Try {
        #Get all Files from the source folder
        $SourceFilesColl = $SourceFolder.Files
        $Ctx.Load($SourceFilesColl)
        $Ctx.ExecuteQuery()
        #Iterate through each file and copy
        Foreach($SourceFile in $SourceFilesColl)
        {
            #Get the source file
            $SourceFile =$Ctx.Web.GetFileByServerRelativeUrl($SourceFile.ServerRelativeUrl)
            $Ctx.Load($SourceFile)
            $Ctx.ExecuteQuery()
            
            #Copy File to destination
            $TargetFileURL = $TargetFolder.ServerRelativeUrl+"/"+$SourceFile.Name
            $SourceFile.CopyTo($TargetFileURL, $True)
            $Ctx.ExecuteQuery()
            Write-host -f Green "Copied File '$($SourceFile.ServerRelativeUrl)' to '$TargetFileURL'"
        }
        #Process Sub Folders
        $SubFolders = $SourceFolder.Folders
        $Ctx.Load($SubFolders)
        $Ctx.ExecuteQuery()
        Foreach($SubFolder in $SubFolders)
        {
            If($SubFolder.Name -ne "Forms")
            {
                #Prepare Target Folder
                $TargetFolderURL = $SubFolder.ServerRelativeUrl -replace $SourceLibrary.RootFolder.ServerRelativeUrl, $TargetLibrary.RootFolder.ServerRelativeUrl
                Try {
                        $Folder=$Ctx.web.GetFolderByServerRelativeUrl($TargetFolderURL)
                        $Ctx.load($Folder)
                        $Ctx.ExecuteQuery()
                    }
                catch {
                        #Create Folder
                        if(!$Folder.Exists)
                        {
                            $Folder=$Ctx.Web.Folders.Add($TargetFolderURL)
                            $Ctx.Load($Folder)
                            $Ctx.ExecuteQuery()
                            Write-host "Folder Added:"$SubFolder.Name -f Yellow
                        }
                    }
                #Call the function recursively
                Copy-AllFiles -SiteURL $SiteURL -SourceFolder $SubFolder -TargetFolder $Folder
            }
        } 
    }
    Catch {
        write-host -f Red "Error Copying File!" $_.Exception.Message
    }
}
#Set Parameter values
$SiteURL="https://crescent.sharepoint.com"
$SourceLibraryName="Project Documents"
$TargetLibraryName="Documents"
#Setup Credentials to connect
$Cred= Get-Credential
$Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)
#Setup the context
$Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Ctx.Credentials = $Credentials
     
#Get the source library and Target Libraries
$SourceLibrary = $Ctx.Web.Lists.GetByTitle($SourceLibraryName)
$Ctx.Load($SourceLibrary)
$Ctx.Load($SourceLibrary.RootFolder)
$TargetLibrary = $Ctx.Web.Lists.GetByTitle($TargetLibraryName)
$Ctx.Load($TargetLibrary)
$Ctx.Load($TargetLibrary.RootFolder)
$Ctx.ExecuteQuery()
#Call the function 
Copy-AllFiles -SiteURL $SiteURL -SourceFolder $SourceLibrary.RootFolder -TargetFolder $TargetLibrary.RootFolder

PnP PowerShell 在 SharePoint Online 中复制文件:

每次复制 SharePoint Online 文档库中的文件可能会很乏味!以下是如何使用 PowerShell 在 SharePoint Online 中自动执行复制文件的过程。


#Config Variables
$SiteURL = "https://Crescent.sharepoint.com/sites/marketing"
$SourceURL= "Shared Documents/Discloser Asia.doc"
$TargetURL = "Shared Documents/Discloser Asia-v2.doc"

#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -Credentials (Get-Credential)

#Copy File to same document library
Copy-PnPFile -SourceUrl $SourceURL -TargetUrl $TargetURL -Force

使用 PowerShell 在 SharePoint Online 中的文件夹之间复制文件

以下是一个将文件从一个文件夹复制到另一个文件夹的 PowerShell 示例:


#Parameters
$SiteURL = "https://crescent.sharepoint.com/sites/marketing"
$SourceURL = "/sites/marketing/Shared Documents/Active/SRS.docx"
$TargetURL = "/sites/marketing/Shared Documents/Categorized/SRS.docx"

#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -Interactive
 
#Copy All Files and Folders from one folder to another
Copy-PnPFile -SourceUrl $SourceURL -TargetUrl $TargetURL -Force

Copy-PnPFile cmdlet 可用于将文件复制到同一库、不同网站集中的不同库之间!


#Config Variables
$SiteURL = "https://Crescent.sharepoint.com/sites/marketing"
$SourceURL= "Shared Documents/Discloser Asia.doc" #Site Relative path
$TargetURL = "/Sites/Sales/Shared Documents/Discloser Asia-v2.doc"

#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -Credentials (Get-Credential)

#Copy File to another site collection
Copy-PnPFile -SourceUrl $SourceURL -TargetUrl $TargetURL -Force 

如果需要在不同网站集之间复制文件,请使用:SharePoint Online:使用 PowerShell 在网站集之间复制文件

使用 PnP PowerShell 在文档库之间复制文件夹

如果您想复制两个文件夹之间的所有文件和子文件夹怎么办?


#Parameters
$SiteURL = "https://crescent.sharepoint.com/sites/marketing"
$SourceFolderURL = "/sites/marketing/Shared Documents/V1"
$TargetFolderURL = "/sites/marketing/Project Document/V1"

#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -Credentials (Get-Credential) #-Interactive

#Copy All Files and Folders from one folder to another
Copy-PnPFile -SourceUrl $SourceFolderURL -TargetUrl $TargetFolderURL -Force

但是,此方法不适用于“RootFolder”对象! (含义:您不能仅调用此 cmdlet 来复制文档库之间的所有文件和文件夹)。

PnP PowerShell 使用元数据复制文档库之间的所有文件和文件夹

想要在库之间复制所有项目时保留元数据吗?没问题!让我向您展示如何创建一个可用于在 SharePoint Online 中复制文件的简单 PowerShell 脚本。假设我们已准备好源文档库和目标文档库,此 PowerShell 脚本会将所有内容及其元数据从源库复制到目标库。


#Function to copy all Items from one library to another
Function Copy-AllDocuments($SourceLibraryName, $TargetLibraryName)
{
    #Get Source and Target Libraries
    $SourceLibrary = Get-PnPList -Identity $SourceLibraryName -Includes RootFolder
    $TargetLibrary = Get-PnPList -Identity $TargetLibraryName -Includes RootFolder
 
    $Web = Get-PnPWeb
    #Calculate Site Relative URL of the Folder
    If($Web.ServerRelativeURL -eq "/")
    {
	    $FolderSiteRelativeUrl = $SourceLibrary.RootFolder.ServerRelativeUrl
    }
    Else
    {      
	    $FolderSiteRelativeUrl = $SourceLibrary.RootFolder.ServerRelativeUrl.Replace($Web.ServerRelativeURL,[string]::Empty)
    }

    #Get All Content from Source Library's Root Folder
    $RootFolderItems = Get-PnPFolderItem -FolderSiteRelativeUrl $FolderSiteRelativeUrl | Where {($_.Name -ne "Forms") -and (-Not($_.Name.StartsWith("_")))}
        
    #Copy Items to the Destination
    $RootFolderItems | ForEach-Object {
        $TargetURL = $TargetLibrary.RootFolder.ServerRelativeUrl
        Copy-PnPFile -SourceUrl $_.ServerRelativeUrl -TargetUrl $TargetURL -Force -OverwriteIfAlreadyExists
        Write-host "`tCopied '$($_.ServerRelativeUrl)'" -f Green    
    }
 
    #Get All Items from Source Library
    $SourceItems = Get-PnPListItem -List $SourceLibraryName -PageSize 500
    $TargetItems = Get-PnPListItem -List $TargetLibraryName -PageSize 500

    ForEach($SourceItem in $SourceItems)
    {
        #Get Metadata from Source Items
        $Metadata = @{
            'Title' = $SourceItem.FieldValues.Title
            'Created'= $SourceItem.FieldValues.Created.DateTime
            'Modified' = $SourceItem.FieldValues.Modified.DateTime
            'Author' = $SourceItem.FieldValues.Author.Email
            'Editor' = $SourceItem.FieldValues.Editor.Email
            }
        #Update Metadata in Target Items
        ForEach($TargetItem in $TargetItems)
        {
            If($SourceItem.FieldValues.FileLeafRef -eq $TargetItem.FieldValues.FileLeafRef)
            {
                Set-PnPListItem -List $TargetLibrary -Identity $TargetItem.Id -Values $Metadata | Out-Null
            }
        }
    }
}
#Connect to PnP Online
$SiteURL = "https://crescent.sharepoint.com/sites/Retail"
Connect-PnPOnline -Url $SiteURL -Interactive
#Call the function to copy all files between document libraries
Copy-AllDocuments -SourceLibraryName "Invoices" -TargetLibraryName "Invoices V2"

该脚本复制给定文档库之间的所有文件和文件夹。要将整个文档库复制到 SharePoint Online 中的另一个网站,请使用:SharePoint Online 将文档库复制到另一个网站 PowerShell

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

取消回复欢迎 发表评论:

关灯