Permission Denied When Trying to Overwrite Hidden File

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.


Hidden files have to be deleted before you can "overwrite" them as Out-File does (without the -Append parameter). Add-Content and Set-Content work around this by modifying the existing file's content without overwriting it. See the docs on the FileMode.Create enum value.

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"

I'm not sure why Out-File is giving this error - it does for me as well. However, Set-Content and Add-Content both work correctly on my system with the -Force parameter:

"New Text" | Add-Content C:\test\Test.txt -Force


"New Text" | Set-Content C:\test\Test.txt -Force

Edited to add: I was curious as to the difference between Out-File and Set-Content, and found this:

Powershell set-content and out-file what is the difference?

It still doesn't quite explain the difference on writing to a hidden file, but may be of interest if you're trying to decide which to use.

Need Your Help

Why doesn't my div inside a span work properly?

html css

I'm writing the following HTML markup:

backbutton event (cordova) not affecting angularjs controller variables as expected

javascript angularjs cordova

I am getting unpredictable results from trying to integrate cordova.js into my angular controller.