使用PowerShell和OData API将文件上载到SharePoint 2010

时间:2015-05-12 15:28:56

标签: powershell sharepoint sharepoint-2010 odata powershell-v3.0

我尝试将文件上传到SharePoint 2010:

Function Add-Attachments()
{

    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$True)]
        [int]$Id,
        [Parameter(Mandatory=$True)]
        [string[]]$Paths
    )

    BEGIN {}
    PROCESS {

        $url = "http://server/resource/_vti_bin/listdata.svc/TheList($Id)/Attachments"

        Foreach ($Path in $Paths) {

            Write-Verbose "Attaching $Path ..."
            $headers = @{
                'Slug' = "TheList|$Id|$(Split-Path $path -Leaf)"
            }

            $Payload = @{filename=(Split-Path $path -Leaf);filecontent=([IO.File]::ReadAllBytes($path))}

            Invoke-WebRequest -Uri $url -Method Post -UseDefaultCredentials -Body $Payload -Headers $headers

        } # Foreach

    } # PROCESS
    END {}

}

Add-Attachments -Id 1234 -Paths 'C:\Users\gandalf\Desktop\test.txt' -verbose

我收到的错误是:

  

Invoke-WebRequest:   发生错误   处理此请求。在   C:\ Users \用户甘道夫\文件\ WindowsPowerShell \脚本\ SP \ SharePoint2010.ps1:382   焦炭:13   + Invoke-WebRequest -Uri $ url -Method Post -UseDefaultCredentials -Bod ...   + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~       + CategoryInfo:InvalidOperation:(System.Net.HttpWebRequest:HttpWebRequest)[Invoke-WebRequest],   引发WebException       + FullyQualifiedErrorId:WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

**编辑**

文件的原始内容:

  

Lorem ipsum dolor坐下来,精神上的精神。 Donec a diam   lectus。 Sed坐在amet ipsum mauris。 Maecenas认为ligula ac quam   viverra nec consectetur ante hendrerit。 Donec et mollis dolor。   Praesent et diam eget libero egestas mattis sit amet vitae augue。南   tincidunt congue enim,ut porta lorem lacinia consectetur。 Donec ut   libero sed arcu vehicula ultricies a non tortor。 Lorem ipsum dolor坐   amet,consectetur adipiscing elit。 Aenean ut gravida lorem。 Turtis   felis,pulvinar a semper sed,adipiscing id dolor。 Pellentesque auctor   nisi id magna consequat sagittis。 Curabitur dapibus enim sit amet elit   pharetra tincidunt feugiat nisl imperdiet。在urna中的自由斗士   ultrices accumsan。 Donec sed odio eros。 Donec viverra mi quis quam   在malesuada arcu rhoncus的pulvinar。 Cum sociis natoque penatibus et   magnis dis parturient montes,nascetur ridiculus mus。在rutrum   累积的ultricies。在sem facilisis semper ac in Mauris vitae nisi   EST。

该脚本确实在服务器上创建了一个文件,但是包含以下内容:

  

文件名= test.txt的&安培; filecontent =的Lorem + ipsum的+悲+坐+阿梅特%2C + consectetur + adipiscing + ELIT + Donec + A +直径+ lectus +桑达+坐+阿梅特+ ipsum的+ mauris +。保护者+ congue + ligula + AC +华富+灵猫+ NEC + consectetur +赌注+ hendrerit。+ Donec +等+油树+悲。+ Praesent +等+直径+ eget +自由人+ egestas +马蒂斯+坐+阿梅德+简历+ augue。+南+ tincidunt + congue + enim%2C + UT + PORTA + LOREM + lacinia + consectetur。+ Donec + UT +自由人+ SED + arcu + vehicula + ultricies + A +非+ tortor。+的Lorem + ipsum的+悲+坐+阿梅特%2C + consectetur + adipiscing + ELIT。+ Aenean + UT +孕妇+ LOREM。+ UT + turpis +蚤%2C +枕+ A +森佩尔+ SED%2C + adipiscing + ID +悲。+ Pellentesque + auctor +耐司+ ID +蚤+ consequat + sagittis。+ Curabitur + dapibus + enim +坐+阿梅德+ ELIT + pharetra + tincidunt + feugiat + nisl + imperdiet。+ UT + convallis +自由人+中+乌仁娜+ ultrices + accumsan。 + Donec + sed的+奥迪奥+性爱。+ Donec +灵猫+ MI + QUIS +财经+枕+在+ malesuada + arcu + rhoncus。+射精+ sociis + natoque + penatibus +等+ magnis + DIS +产妇+特斯%2C + nascetur + ridiculus +亩。+在+ rutrum + accumsan + ultricies。+ Mauris +履历+硅化镍+在+ SEM + facilisis +森佩尔+ AC +在+ EST。

我错过了什么?我需要包含内容长度吗?设置MIME类型?

1 个答案:

答案 0 :(得分:2)

要创建附件资源,必须指定以下属性:

Endpoint Uri: http://server/site/_vti_bin/listdata.svc/entityset(itemid)/Attachments
Method: POST
Headers:
   Slug: "entityset|itemid|name"
   ContentType: */* 
Body: content

话虽如此,我在提供的示例中指出body参数($payload)无效。

以下示例演示了如何通过SharePoint 2010 REST接口上载附件文件:

Function Add-Attachments()
{

    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$True)]
        [string]$WebUrl, 
        [Parameter(Mandatory=$True)]
        [string]$ListName, 
        [Parameter(Mandatory=$True)]
        [int]$ItemId,
        [Parameter(Mandatory=$True)]
        [string]$SourcePath
    )

    BEGIN {}
    PROCESS {
        $endpointUri = New-Object System.Uri("$WebUrl/_vti_bin/listdata.svc/$ListName($ItemId)/Attachments")
        $fileName = (Split-Path $SourcePath -Leaf)
        $fileContent = ([IO.File]::ReadAllBytes($SourcePath))
        $headers = @{
                 'Slug' = "$ListName|$ItemId|$fileName";
        }

        Invoke-WebRequest -Uri $endpointUri -Method Post -UseDefaultCredentials -Body $fileContent -Headers $headers -ContentType "*/*"

    } # PROCESS
    END {}

}

用法:

Add-Attachments -WebUrl "http://contoso.intranet.com/" -ListName "Tasks" -ItemId 1 -SourcePath "C:\Users\user\Documents\SharePointUserGuide.docx" -verbose

<强>更新

在通过Fiddler进行一些分析后,确定适当的端点URL应为:

/_vti_bin/listdata.svc/Attachments HTTP/1.1

而不是:

/_vti_bin/listdata.svc/Tasks(<id>)/Attachments HTTP/1.1

修改后的示例

Function Add-Attachments()
{

    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$True)]
        [string]$WebUrl, 
        [Parameter(Mandatory=$True)]
        [string]$ListName, 
        [Parameter(Mandatory=$True)]
        [int]$ItemId,
        [Parameter(Mandatory=$True)]
        [string]$SourcePath
    )

    BEGIN {}
    PROCESS {
        $endpointUri = New-Object System.Uri("$WebUrl/_vti_bin/listdata.svc/Attachments")  
        $fileName = (Split-Path $SourcePath -Leaf)
        $fileContent = ([IO.File]::ReadAllBytes($SourcePath))
        $headers = @{
                 'Slug' = "$ListName|$ItemId|$fileName";
        }

        Invoke-WebRequest -Uri $endpointUri -Method Post -UseDefaultCredentials -Body $fileContent -Headers $headers -ContentType "*/*"

    } # PROCESS
    END {}

}