Add an attachment to the SharePoint 2010 list item using web service in powershell

Steps Involved:

  1. Open SharePoint 2010 Management Shell by going to Start | All Programs | SharePoint | Microsoft SharePoint 2010 Products | SharePoint 2010 Management Shell (Run as Administrator).
  2. Run the following script.

Powershell Script:

 

## Input Parameters required for attaching a file to the list item

      $uri="http://serverName:10736/sites/ECT/_vti_bin/Lists.asmx?wsdl"

      [string] $listItemId="3"

      [string] $listName="List"

      [string] $fPath = "D:\Lists.xml"   

     

      ## Check if the file exists in the path specified

      if([System.IO.File]::Exists($fPath))

      {

            ## Read the file

            $fStream=[System.IO.File]::OpenRead($fPath)

            [String] $fName=$fStream.Name

            [System.Byte[]]$bytes=New-Object -TypeName System.Byte[] -ArgumentList $fStream.Length

            $fStream.Read($bytes, 0, [int]$fStream.Length)

          $fStream.Close()

           

            ## Attach the file to the list item using web service

            $listWebServiceReference = New-WebServiceProxy -Uri $uri -UseDefaultCredential

            Write-Host -ForegroundColor Magenta "Adding the attachement to the list item........."

            $listWebServiceReference.AddAttachment($listName,$listItemId,$fName,$bytes)

            Write-Host -ForegroundColor Green $fName " is attached successfully to the list item"      

      }

      else

      {

          Write-Host -ForegroundColor Yellow "File does not exists in the specified path " $fPath

      }

     

 

 



For more information on New-WebServiceProxy please refer http://technet.microsoft.com/en-us/library/dd315258.aspx.