Access denied powershell

Michelle Matthias 1 Reputation point
2022-09-28T12:14:52.593+00:00

I have a script that has been running for years that stopped working last week - I have gotten to the point I know where it is messing up but can't figure out what to do to fix it.

$Downfiles = Get-ChildItem –Path $localPath
if ($Downfiles -ne $null) #download directory pocess
{
foreach($file in $Downfiles)
{
$content = [System.IO.File]::ReadAllText($file.fullname).Replace("`n","~")
[System.IO.File]::WriteAllText($file.fullname, $content)
}

it is the ReadAllText that is the issue

Here is the error

Get-Content : Access to the path 'C:\gensrvnt\Imports\prod\DOWNLOADED\temp' is denied.
At C:\GENSRVNT\Bin\Batch\FTP_PROCESS_09242022_MM.ps1:15 char:21

  • $content = ($_ | Get-Content)
  • ~~~~~~~~~~~
  • CategoryInfo : PermissionDenied: (C:\gensrvnt\Imports\prod\DOWNLOADED\temp:String) [Get-Conte
    nt], UnauthorizedAccessException
  • FullyQualifiedErrorId : GetContentReaderUnauthorizedAccessError,Microsoft.PowerShell.Commands.GetConte
    ntCommand
Windows for business Windows Server User experience PowerShell
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. MotoX80 36,291 Reputation points
    2022-09-28T12:30:54.447+00:00

    You probably have a file that is flagged as read only.

    Downfiles = Get-ChildItem –Path $localPath   
    if ($Downfiles -ne $null) #download directory pocess  
    {  
        foreach($file in $Downfiles)  
        {  
            "Processing {0}" -f $file.fullname  
            $content = [System.IO.File]::ReadAllText($file.fullname).Replace("`n","~")  
            Set-ItemProperty -Path $file.fullname -Name IsReadOnly -Value $false  
            [System.IO.File]::WriteAllText($file.fullname, $content)  
        }  
    }  
    
    0 comments No comments

  2. Rich Matheisen 47,901 Reputation points
    2022-09-28T14:46:09.84+00:00

    First, change the conditional statement on line #2 from $Downfiles -ne $null to $null -ne $Downfiles to avoid comparing the contents of the array instead of the contents of the variable $Downfiles.

    Next, is it possible that a child directory has been added to the directory path in $localPath? If you only want the files in that directory, add the "-File" switch to the Get-ChildItem cmdlet.

    Lastly, the error occurs on line 15, but there aren't 15 lines in the code you posted, AND it's a Get-Content cmdlet that's failing in that error message, not the ReadAllText method.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.