Powershell:使用System.Net.WebClient.UploadFile将文件上载到SharePoint时发生WriteErrorException

Powershell:使用System.Net.WebClient.UploadFile将文件上载到SharePoint时发生WriteErrorException,sharepoint,powershell,sharepoint-2010,Sharepoint,Powershell,Sharepoint 2010,我正在尝试使用下面的代码将一个文件从本地上传到SharePoint。但不知怎的,这个错误消息被抛出,这让我想知道原因: Exception calling "UploadFile" with "3" argument(s): "An exception occurred during a WebClient request." + CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException

我正在尝试使用下面的代码将一个文件从本地上传到SharePoint。但不知怎的,这个错误消息被抛出,这让我想知道原因:

Exception calling "UploadFile" with "3" argument(s): 
"An exception occurred during a WebClient request."
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId :              Microsoft.PowerShell.Commands.WriteErrorException,CopyFileToSharePoint.ps1
有人有什么想法吗

  • 运行脚本的用户具有上载文件的权限,例如以交互方式使用IE
  • 不,这是一个远程服务器,因此我不能使用Microsoft.SharePoint类
代码

#Copy the file to the destination on SharePoint using WebClient
$SourceFile = $SourcePath + "\" + $FileName
$DestinationFile = $DestinationPath + "/" + $FileName

$client = new-object System.Net.WebClient
$client.UseDefaultCredentials=$true

if ( -not (Test-Path $DestinationPath) ) {
New-Item $DestinationPath -Type Directory  | Out-Null
}

$result |% {
Write-Host "Uploading $SourceFile to $DestinationFile"

try{
    $client.UploadFile($SourceFile, $DestinationFile)
}
catch{
    #one simple retry...
    try{
        $client.UploadFile($SourceFile, $DestinationFile)
    }
    catch{
        write-error "Failed to upload $SourceFile, $_"
    }
}
}   

解决了!最终似乎起作用的是设置contenttype:

$client.ContentType = "application/octet-stream";
这不知怎么解决了问题。 从以下线索中获得了尝试的想法:

此外,在运行UploadFile命令之前,您上载的文件应在SharePoint库中“签出”。否则,UploadFile将抛出上述MethodException错误,共3个参数。我手动切换SharePoint库设置“编辑前是否允许签出文档?”重新创建了此错误。
但我不知道我们是否可以通过编程方式使用System.Net.WebClient进行签出/签入。(但在文档中找不到任何内容)

可能与此无关,但您的重试是“下载”文件,而不是上载。错误表示您正在传递3个参数。能否打印$sourceFile和$DestinationFile?它看起来像什么?是的,我道歉。复制了一个本地版本,但仍然有打字错误。第二个下载文件应该是uploadfile。我修复了原始帖子(我知道,有点可疑,但在这个帖子中增加了清晰性)$SourceFile:D:\temp\test.csv$DestinationFile=Hmm,有点不对劲$DestinationFile不能这样设置,对吗?我怀疑%20(空格字符)是您的问题,并导致上传认为您的路径是3部分。你能打印$DestinationFile吗?