我已经搜索了一段时间,似乎无法理解为什么会发生这种情况。
我有一个维护文件的脚本。我想隐藏该文件,但是在尝试覆盖它时更改文件属性会导致权限问题。
设置是这样的:
"Test Text" | Out-file 'C:\Test\Test.txt' -Force
Set-ItemProperty 'C:\Test\Test.txt' -name Attributes -Value "Hidden"
现在,如果我尝试像这样覆盖它,则会出现以下错误:
"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
但是权限似乎不是问题,因为我可以获取内容并且可以很好地删除文件。
Get-Content 'C:\Test\Test.txt'
rm 'C:\Test\Test.txt' -force
解决方法是删除文件,然后编写我的新文件,但我更愿意保留现有文件,并在可能的情况下添加到其中。
最佳答案
必须先删除隐藏文件,然后才能将它们“覆盖”为 Out-File
确实(没有 -Append
参数)。 Add-Content
和 Set-Content
通过修改现有文件的内容而不覆盖它来解决这个问题。见 docs on the FileMode.Create枚举值。
关于powershell - 尝试覆盖隐藏文件时权限被拒绝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20155375/