Friday, December 23, 2011

VBScript : pathIsBusy()

Sometimes i need a function that checks if a file is busy or not. Instead of two seperate functions folderIsBusy and fileIsBusy i made a pathIsBusy that can check for both.
It uses old technique of attempting to rename the file or folder. If the path is busy you cannot rename it, so the result is simply based on the succes of the renaming process.

If anyone got a better way of doing this, i'd be happy to learn about it.

Function pathIsBusy(thePath)
 Dim fso : set fso = CreateObject("Scripting.FileSystemObject")
 Dim tempPath
 Dim wasError
 Dim isAFolder
 Dim fPath : fPath = Trim(thePath)
 
 if fso.FolderExists(fPath) = True Then
  ' Remove last "\" if it exists
  if Right(fPath,1) = "\" Then fPath = Left(fPath,Len(fPath)-1) 
  isAFolder = True
 ElseIf fso.FileExists(fPath) = True Then
  isAFolder = false
 Else
  Exit Function
 End If
 
 ' Make temporary filepath
 tempPath = fPath & "_rnmtmp_" & int(Rnd*10) & int(Rnd*10) & int(Rnd*10) & int(Rnd*10)
 
 On Error Resume Next
  Err.Clear
  if isAFolder = True Then
   fso.MoveFolder fPath, tempPath  
  Else  
   fso.MoveFile fPath, tempPath
  End If
  
 if  Err.Number <> 0  then   
  wasError = True
 Else
  wasError = False
  if isAFolder = True Then
   fso.MoveFolder tempPath, fPath   
  Else
   fso.MoveFile tempPath, fPath
  End If
 End If
 
 fso = nothing
 pathIsBusy = wasError
End Function


'==EXAMPLE==
wscript.echo "c:\windows\ is busy: " & pathIsBusy("c:\windows\")
wscript.echo "c:\pagefile.sys is busy: " & pathIsBusy("c:\pagefile.sys")
wscript.echo "c:\windows\system.ini is busy: " & pathIsBusy("c:\windows\system.ini")


'

No comments:

Post a Comment