Forum Discussion

Scott Oxendine's avatar
Scott Oxendine
Brass Contributor
Jun 14, 2017
Solved

Using PnP PowerShell to attach a file to an item

Can somepone provide an example of a successful upload of a file as an attachment to a list item using PnP PowerShell? I am struggling getting $item.attachmentFiles.add() to work. I don't seem to be ...
  • Manidurai Mohanamariappan's avatar
    Manidurai Mohanamariappan
    Jun 17, 2017

    Try this script

     

    function writeItem(
    $itemTitle,
    $itemOther,
    $attachments
    ) {
    # check if file exists first
    $items=Add-PnPListItem -List testlist
    
    $newListItem = Set-PnPListItem -Identity $Items.Id -List testlist -Values @{"Title" = $itemTitle; "other" = $itemOther}
    
    
    for ($a=0; $a -lt $attachments.length; $a++) {
    #Write-host " " $attachments[$a]
    writeAttachment -item $items -fileWithPath  $attachments[$a]
    }
    
    }
    
    function writeAttachment($item, $fileWithPath)
    {
    
    $ctx=Get-PnPContext
    $memoryStream = New-Object IO.FileStream($fileWithPath,[System.IO.FileMode]::Open)
    $fileName = Split-Path $fileWithPath -Leaf
    $attachInfo = New-Object -TypeName Microsoft.SharePoint.Client.AttachmentCreationInformation
    $attachInfo.FileName = $fileName
    $attachInfo.ContentStream = $memoryStream
    $attFile = $item.attachmentFiles.add($attachInfo)
    $ctx.load($attFile)
    $ctx.ExecuteQuery()
    }
    
    Connect-PnPOnline -url https://tenantname.sharepoint.com/sites/contosobeta
    
    $Att=@("C:\copyfile.csv","C:\AllSubsitegrouppermission.csv","C:\AllUserWithLicenseType.csv")
    
    writeItem -itemTitle "test6789" -itemOther "efgh" -attachments $Att 

Resources