You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell跨SharePoint复制文件:双连接建立方法咨询

跨SharePoint复制文件的PowerShell解决方案

嘿,我来帮你搞定这个跨SharePoint复制文件的问题!看起来你已经拿到了待复制的文件变量$cow,接下来咱们一步步完成双站点连接和文件传输:

1. 先准备好PnP PowerShell工具

这是操作SharePoint最常用的PowerShell模块,如果你还没安装,先跑这个命令:

Install-Module -Name PnP.PowerShell -Force -AllowClobber

安装完成后导入模块:

Import-Module PnP.PowerShell

2. 分别建立源和目标站点的连接

咱们需要同时保持两个站点的连接上下文,这样才能在两者之间传输文件。用-ReturnConnection参数把连接对象存到变量里:

# 连接源SharePoint站点,替换成你的源站点URL
$sourceConnection = Connect-PnPOnline -Url "https://your-source-sharepoint-site.sharepoint.com/sites/SourceSite" -Interactive -ReturnConnection

# 连接目标SharePoint站点,替换成你的目标站点URL
$targetConnection = Connect-PnPOnline -Url "https://your-target-sharepoint-site.sharepoint.com/sites/TargetSite" -Interactive -ReturnConnection

提示:-Interactive会弹出登录窗口,如果你用的是服务账号,可以换成-Credentials参数传入凭据。

3. 从源站点读取文件内容

假设$cow是你之前通过Get-PnPFile获取的源文件对象,咱们先把它的内容读成字节数组:

# 读取源文件的二进制内容
$fileContent = Get-PnPFile -Url $cow.ServerRelativeUrl -Connection $sourceConnection -AsByteArray

如果$cow只是文件路径字符串,那直接把$cow代入-Url参数就行。

4. 上传到目标站点的Documents目录

最后把读取到的内容上传到目标站点的Documents库,注意替换目标库的相对路径(默认是/sites/TargetSite/Documents,如果你的库名称不同要调整):

# 上传文件到目标Documents目录
Add-PnPFile -Path $cow.Name -Folder "/sites/TargetSite/Documents" -Content $fileContent -Connection $targetConnection

一些实用的额外处理

  • 避免覆盖同名文件:可以先检查目标目录是否已有该文件,再决定是否上传
$targetFileExists = Get-PnPFile -Url "/sites/TargetSite/Documents/$($cow.Name)" -Connection $targetConnection -ErrorAction SilentlyContinue
if (-not $targetFileExists) {
    Add-PnPFile -Path $cow.Name -Folder "/sites/TargetSite/Documents" -Content $fileContent -Connection $targetConnection
} else {
    Write-Host "文件 $($cow.Name) 已存在于目标站点,跳过上传"
}
  • 超大文件处理:如果文件超过100MB,建议用-ChunkSize参数分片上传,避免超时
Add-PnPFile -Path $cow.Name -Folder "/sites/TargetSite/Documents" -Content $fileContent -Connection $targetConnection -ChunkSize 5MB

内容的提问来源于stack exchange,提问作者Jorge Tejeda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:44:07