5

I have to add the local files to list item as an attachment with PowerShell. While reading the file I got an error "Access Denied" as below-

**Exception calling "ReadAllBytes" with "1" argument(s): "Access to the path 'D:\Projects\Test\List Data\Attachments\3' is denied."

Code Snippet-

$filePath = "D:\Projects\Test\List Data\Attachments\" + $item.ID
$bytes = [System.IO.File]::ReadAllBytes($filePath)
$item.Attachments.Add([System.IO.Path]::GetFileName($filePath),$bytes)  
$item.Update()

How to fix this?

2 Answers 2

4

Make sure the current user have access to D:\Projects\Test\List Data\Attachments\ by doing the following

  • Right click in this folder >
  • Select sharing with> provide the user that you have used to run PowerShell.
  • Set permission level to can Read and Write.
  • Try to run the script again, it should be working.

Update

I have noticed that you didn't pass the extension of your file , $filePath = "D:\Projects\Test\List Data\Attachments\" + $item.ID try to concatenate the extension like $filePath = "D:\Projects\Test\List Data\Attachments\" + $item.ID +".the file extension" , maybe this is the reason !

7
  • I have not used any user to run the powerShell. Windows user Administrator have the full rights to Read and Write.
    – Ram
    Dec 23, 2016 at 6:35
  • are you using SharePoint management shell to run this script ? Dec 23, 2016 at 6:41
  • No, I am using Windows PowerShell ISE.
    – Ram
    Dec 23, 2016 at 6:44
  • in my case, I tried to run SharePoint management shell via farm account and provide the farm account read and write to this folder Dec 23, 2016 at 6:46
  • The user I am using have the full rights!
    – Ram
    Dec 23, 2016 at 6:48
2

I was missed to iterate the files in the folder, so it gives the error.

The below is the solution which I got from here

        $files = [IO.Directory]::GetFiles($filePath)
        ForEach($file in $files)
        {
        Write-Host "File Name = " $file
        $bytes = [System.IO.File]::ReadAllBytes($file)
        $row.Attachments.Add([System.IO.Path]::GetFileName($file), $bytes)
        }
        $row.Update()

Hope for the best!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.