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)

How to fix this?


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.


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 !

| improve this answer | |
  • I have not used any user to run the powerShell. Windows user Administrator have the full rights to Read and Write. – Ram Dec 23 '16 at 6:35
  • are you using SharePoint management shell to run this script ? – Mohamed El-Qassas MVP Dec 23 '16 at 6:41
  • No, I am using Windows PowerShell ISE. – Ram Dec 23 '16 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 – Mohamed El-Qassas MVP Dec 23 '16 at 6:46
  • The user I am using have the full rights! – Ram Dec 23 '16 at 6:48

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)

Hope for the best!

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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