Permission Denied When Trying to Overwrite Hidden File

powershell, powershell-3.0

Solution

Keith provided a link that explains the permissions issue. Below is my solution to the current problem

Because maintaining the create date of the original file is needed, the workaround I have resorted to is to unhide the file, write to it, then set it back to hidden.

Set-ItemProperty 'C:\Test\Test.xml' -name Attributes -Value "Normal"

$myobject | Export-CliXml 'C:\Test\Test.xml' -Force

Set-ItemProperty 'C:\Test\Test.xml' -name Attributes -Value "Hidden"

Problem

I have been searching for a while and can't seem to understand why this is happening. I have a script that maintains a file. I want to keep that file hidden, but changing the file attribute is causing permissions problems when trying to overwrite it. Setup is this: ``` "Test Text" | Out-file 'C:\Test\Test.txt' -Force Set-ItemProperty 'C:\Test\Test.txt' -name Attributes -Value "Hidden" ``` Now if I try to overwrite it like so I get the following error: ``` "New Text" | Out-file 'C:\Test\Test.txt' -Force ``` Out-file : Access to the path 'C:\Test\Test.txt' is denied. At line:1 char:15 + "Test Text" | Out-file 'C:\Test\Test.txt' -Force + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : OpenError: (:) [Out-File], UnauthorizedAccessException + FullyQualifiedErrorId : FileOpenFailure,Microsoft.PowerShell.Commands.OutFileCommand But permissions don't seem to be the issue because I can get the content and I can remove the file just fine. ``` Get-Content 'C:\Test\Test.txt' rm 'C:\Test\Test.txt' -force ``` The workaround is to remove the file then write my new one, but I would prefer to maintain the existing file and just add to it if possible.

Original source

Related problems