如何在不更改文件或使用第三方工具的情况下锁定 Windows 中的文件?

mar*_*gle 28 windows-7 filesystems lock

有没有办法使用板载工具锁定文件,使其不能被删除或覆盖?

为了测试复制脚本,我需要lock files temporarily检查脚本中的错误处理。直到 XP 我使用在 debug.exe 中加载文件来锁定它。

Windows 7(及更高版本)有办法吗?

编辑
我知道有程序这样做。我的问题是 Windows 中是否有内置机制。有时我必须检查 PC 上的脚本,不想为此安装新程序。

Edit2
这里也有很好的建议:如何有目的地独占锁定文件?,但是,这需要第 3 方工具或更改要锁定的文件。

Dan*_*Dan 52

我认为 PowerShell 可能是实现这一目标的最佳方式。类似于以下内容:

#Specify the file name
$fileName = "C:\myfile.txt"

#Open the file in read only mode, without sharing (I.e., locked as requested)
$file = [System.io.File]::Open($fileName, 'Open', 'Read', 'None')

#Wait in the above (file locked) state until the user presses a key
Write-Host "Press any key to continue ..."
$null = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")

#Close the file (This releases the current handle and unlocks the file)
$file.Close()
Run Code Online (Sandbox Code Playgroud)

暂停时,上述脚本在尝试打开“myfile.txt”时会导致以下提示:

在此处输入图片说明

  • 注意 `$host.UI.RawUI.ReadKey(...)` 将在 PowerShell ISE 中失败,因为 ReadKey 没有为 ISE 实现。解决方法是`[void](Read-Host 'Press Enter to continue')`。与用户必须按 Enter 而不是任何键不完全相同。但是,对于大多数用途来说已经足够了。解决方法来自这篇博文:http://jeffwouters.nl/index.php/2016/06/powershell-press-any-key-to-continue/ (3认同)
  • 伟大的!谢谢!令我感到羞耻的是,我必须承认我是在 powershell 中开发的,并没有考虑为此使用 .net 类。[我希望不会再进一步​​:-)] (2认同)