This article describes how to force overwriting a read-only file when you use PowerShell to write a file.
D:\2.txt is a read-only file, and if I run a out-file output statement, I get an error message:
Copy Code code as follows:
PS c:\users\spaybow> "" | Out-file-append D:\2.txt
Out-file: Access to Path "D:\2.txt" was denied.
Location: 1 Characters: 14
+ "" | Out-file <<<<-append D:\2.txt
+ Categoryinfo:openerror: (:) [Out-file], Unauthorizedaccessexc
Eption
+ Fullyqualifiederrorid:fileopenfailure,microsoft.powershell.commands.ou
Tfilecommand
"Access to the path" D:\2.txt "is denied" because this 2.txt is a read-only file.
Sometimes, we can not control so much, must be mandatory coverage, how can God block kill God, Buddha block kill Buddha? Fortunately, Out-file also provides a-force parameter that, after joining, can be written to the content regardless of whether the file is read-only.
Copy Code code as follows:
PS c:\users\spaybow> "" | Out-file-append-force D:\2.txt
PS c:\users\spaybow>
No error is the implementation of success!
Also notice here that after executing the command to write the file, check out the d:\2.txt, and I find that it is still a read-only state. This state has not been corrupted because it was written to the content.
Also, if the current user does not have write access to the file, the content cannot be written to the file even if the-force parameter is used.
about how PowerShell to write content to read-only file, this article introduces so much, hope to help you, thank you!