如何检查文件是否被另一个进程使用 - Powershell
我正在试图找到一个解决方案来检查另一个进程是否正在使用某个文件。我不想读取文件的内容,例如在7GB文件上,这可能需要一段时间。目前我正在使用下面提到的功能,这并不理想,因为脚本需要大约5-10分钟来检索值。如何检查文件是否被另一个进程使用 - Powershell
function checkFileStatus($filePath)
{
write-host (getDateTime) "[ACTION][FILECHECK] Checking if" $filePath "is locked"
if(Get-Content $filePath | select -First 1)
{
write-host (getDateTime) "[ACTION][FILEAVAILABLE]" $filePath
return $true
}
else
{
write-host (getDateTime) "[ACTION][FILELOCKED] $filePath is locked"
return $false
}
}
任何帮助,将不胜感激
创建了解决上述问题的功能:
function checkFileStatus($filePath)
{
write-host (getDateTime) "[ACTION][FILECHECK] Checking if" $filePath "is locked"
$fileInfo = New-Object System.IO.FileInfo $filePath
try
{
$fileStream = $fileInfo.Open([System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [System.IO.FileShare]::Read)
write-host (getDateTime) "[ACTION][FILEAVAILABLE]" $filePath
return $true
}
catch
{
write-host (getDateTime) "[ACTION][FILELOCKED] $filePath is locked"
return $false
}
}
检查这个脚本在poschcode.org:
filter Test-FileLock {
if ($args[0]) {$filepath = gi $(Resolve-Path $args[0]) -Force} else {$filepath = gi $_.fullname -Force}
if ($filepath.psiscontainer) {return}
$locked = $false
trap {
Set-Variable -name locked -value $true -scope 1
continue
}
$inputStream = New-Object system.IO.StreamReader $filepath
if ($inputStream) {$inputStream.Close()}
@{$filepath = $locked}
}
仅供参考,这不是一个PoshCode链接。 – 2012-02-22 15:51:58
固定,错误的粘贴网址 – 2012-02-22 16:41:16
谢谢,在链接的帮助下,我创建了一个新的功能来完成所需的功能。 – user983965 2012-02-22 18:43:45
,因为你不想读文件,我会建议使用像的Sysinternals实用程序处理.exe,它将为进程吐出所有打开的句柄。你可以从这里下载Handle.exe:
http://technet.microsoft.com/en-us/sysinternals/bb896655
你可以不带任何参数运行Handle.exe,它将返回所有打开的文件句柄。您可以根据需要解析输出,或者仅将输出与完整文件路径进行匹配。
我用它来检查文件是否被锁定或没有该功能:
function IsFileLocked([string]$filePath){ Rename-Item $filePath $filePath -ErrorVariable errs -ErrorAction SilentlyContinue return ($errs.Count -ne 0) }
function IsFileAccessible([String] $FullFileName)
{
[Boolean] $IsAccessible = $false
try
{
Rename-Item $FullFileName $FullFileName -ErrorVariable LockError -ErrorAction Stop
$IsAccessible = $true
}
catch
{
$IsAccessible = $false
}
return $IsAccessible
}
在你的答案中添加一些评论。 – HDJEMAI 2017-02-21 23:37:11
非常感谢您的代码。这非常有用。我正在使用它来测试共享网络位置上的文件是否可用。每隔几天他们就会向该位置上传一个新的大文件(上传需要几个小时),并且我想确保上传完成,以便我可以安全地将该文件复制并下载到本地计算机。你看到我的概念有什么缺陷吗? – FrozenLand 2013-10-16 18:00:26
是否有一个原因在退出之前不会调用'$ fileStream.Dispose()'? – user2426679 2016-01-25 14:40:43
@ user2426679我读过垃圾收集器会照顾它,除非你在特定时间范围内创建太多对象 – 2017-06-21 07:39:11