使用PowerShell下载SharePoint Online Excel文件遇DLL缺失错误求助
错误原因
出现的报错是因为本地未安装SharePoint Client Side Object Model(CSOM)组件,或者脚本指定的DLL路径不存在。你脚本里的路径是SharePoint Server本地部署后的默认路径,但针对SharePoint Online,需要单独安装CSOM组件或通过其他方式获取所需DLL。
解决方案
方案1:安装SharePoint Online CSOM组件
- 下载并安装官方的SharePoint Online Client Components SDK,选择适配你PowerShell版本的最新版本;
- 安装完成后,DLL默认路径即为脚本中指定的
C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\,此时Add-Type命令可正常执行。
方案2:通过NuGet获取DLL(无需安装组件)
如果不想安装CSOM组件,可直接从NuGet获取所需文件:
- 搜索
Microsoft.SharePointOnline.CSOM并下载对应的nupkg包; - 将nupkg后缀改为zip并解压,找到
lib\net45\目录下的Microsoft.SharePoint.Client.dll和Microsoft.SharePoint.Client.Runtime.dll; - 将两个DLL复制到本地任意路径(如
C:\SPOModules\),修改脚本中的Add-Type路径:Add-Type -Path "C:\SPOModules\Microsoft.SharePoint.Client.dll" Add-Type -Path "C:\SPOModules\Microsoft.SharePoint.Client.Runtime.dll"
脚本其他修正点
除了DLL问题,你的脚本还有两处需要调整:
- SiteURL错误:当前
$SiteURL设为文档库URL,需改为SharePoint站点根URL,例如https://domain.sharepoint.com/或对应子站点URL; - TargetFilePath错误:仅指定目录会导致文件创建失败,需补充文件名,例如
C:\temp\testFileRealData02.xlsx。
修正后的完整脚本
#Load SharePoint CSOM Assemblies Add-Type -Path "C:\SPOModules\Microsoft.SharePoint.Client.dll" Add-Type -Path "C:\SPOModules\Microsoft.SharePoint.Client.Runtime.dll" #Function to copy a given sourcefile to downloadpath Function Download-FileFromLibrary() { param ( [Parameter(Mandatory=$true)] [string] $SiteURL, [Parameter(Mandatory=$true)] [string] $SourceFileURL, [Parameter(Mandatory=$true)] [string] $TargetFilePath ) Try { #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 #sharepoint online powershell download file from library $FileInfo = [Microsoft.SharePoint.Client.File]::OpenBinaryDirect($Ctx,$SourceFileURL) $WriteStream = [System.IO.File]::Open($TargetFilePath,[System.IO.FileMode]::Create) $FileInfo.Stream.CopyTo($WriteStream) $WriteStream.Close() Write-host -f Green "File '$SourceFileURL' Downloaded to '$TargetFilePath' Successfully!" } Catch { write-host -f Red "Error Downloading File!" $_.Exception.Message } } #Set parameter values $SiteURL="https://domain.sharepoint.com/" # 改为站点根URL $SourceFileURL="/Shared%20Documents/testFileRealData02.xlsx" #Server Relative URL $TargetFilePath="C:\temp\testFileRealData02.xlsx" # 补充文件名 #Call the function to download file Download-FileFromLibrary -SiteURL $SiteURL -SourceFileURL $SourceFileURL -TargetFilePath $TargetFilePath
内容的提问来源于stack exchange,提问作者Muhammad Usman Adil
相关产品推荐
相关产品推荐

