Welcome to deBUG.to Community where you can ask questions and receive answers from Microsoft MVPs and other experts in our community.
0 like 0 dislike
30.5k views
in PowerShell by 16 25 33
edited by

I got access to the path is denied when I tried to write content to CSV file using Add-Content in PowerShell

Add-Content : Access to the path 'C:\myfloder' is denied.
At C:\Users\spfarm\Desktop\PS Scripts\Export Documents Versions Details with Comments In SharePoint.ps1:29 char:1
+ Add-Content -Path $FolderPath -Value "First Name,Last Name, Modi ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : PermissionDenied: (C:\myfloder:String) [Add-Content], UnauthorizedAccessException
    + FullyQualifiedErrorId : GetContentWriterUnauthorizedAccessError,Microsoft.PowerShell.Commands.AddContentCommand

This is my PowerShell script

$Path = "C:\myfolder\file.csv"
New-Item -ItemType Directory -Path $Path

#add a row in CSV
Add-Content -Path $Path -Value "First Name,Last Name, Modified Date"

How to fix this?


1 Answer

1 like 0 dislike
by 54 119 241
selected by
 
Best answer

Access to the path is denied PowerShell

To solve the Access to the path is denied PowerShell problem, you should make sure that:

  1. The Windows PowerShell is running as Administrator.
    run PowerShell as administrator
  2. The provided path is correct in Add-Content.
  3. The file is not located directly in the c:\ drive, it should be inside a folder in the root drive.

If you need to create your file in c:\ drive directly, make sure that you have added Set-ExecutionPolicy "Unrestricted" at the beginning of your PowerShell Script.


Add-Content: Access to the path is denied.

As per your PowerShell script, you are trying to create a directory, not a file then you have set a folder path rather than a file path in Add-Content and that will cause this error 'Add-Content : Access to the path is denied."

In your case, you must make sure that you have set the -Path in Add-Content to a valid file path. so try to change your PowerShell script to the following:

#Create a folder
$Path = "C:\myfolder"
New-Item -ItemType Directory -Path $Path

# Create a file
$FilePath = "$Path\file.csv"
New-Item -ItemType file -Path $FilePath

# Check if the path is exist
if(Test-path $FilePath)
  {
     #add a row in CSV to the correct file path
    Add-Content -Path $FilePath -Value "First Name,Last Name, Modified Date"
  }
by 16 25 33
1 0
You are right, I was passing the folder pass instead of the file path. Thank you!
If you don’t ask, the answer is always NO!
...