用 PowerShell 检查文件是否被占用
通过 try/catch 尝试用 .NET File.Open 以独占方式打开文件,判断是否有其他程序正在使用它。
在 try 块中执行 [System.IO.File]::Open(路径, 'Open', 'ReadWrite', 'None'),抛出异常就说明文件被占用。
01命令
命令
$ try {
$fs = [System.IO.File]::Open('C:\Temp\report.xlsx', 'Open', 'ReadWrite', 'None')
$fs.Close(); 'File is NOT locked'
} catch { 'File IS locked: ' + $_.Exception.Message }02作用说明
以 FileShare.None 方式请求打开文件,只有在没有任何程序占用时才会成功,一旦抛出异常就说明文件被锁定,而测试用的句柄会立即关闭、不会影响其他程序。如果确实被占用,可以用资源监视器的"CPU→关联的句柄"搜索文件名找出占用它的程序。刚在 Excel/Word 里打开的表格或浏览器里预览的 PDF 自然会被判定为占用中。
03风险
!注意: 这种检查会真实地打开再关闭文件一次;对正被程序写入的文件理论上存在极小的时机冲突,不要高频循环执行。
04撤销
✓无需撤销——该命令不会改变持久状态。
05来源
- FileStream Class依据: FileStream with FileShare.None throws IOException when the file is already open elsewhere, the mechanism behind the lock test.
- File.Open(String, FileMode, FileAccess, FileShare) Method依据: File.Open with FileShare.None throws IOException when another process holds the file open, which is the basis of the lock test.
最后验证: 2026-09-18 · 分类: 文件与文件夹