Page 1 of 2 12>
Topic Options
#76988 - 2003-10-07 11:51 PM Detect New File Presence
ShaneEP Moderator Offline
MM club member
*****

Registered: 2002-11-29
Posts: 2127
Loc: Tulsa, OK
Hello gents...

Got a request to create a script that will run continuously and give an alert whenever a new file is detected in a certain directory.

I have written the below that seems to work...Except for when the newest file is deleted..It then thinks the next newest (before the one deleted) is a new file.

I cant seem to think of a way to get around it. Any suggestions? Or if anyone know of a better way to do it...please let me know.



$directory = "L:\ScannedDocs\"
Dim $file$filedate$line$newfile$newfiledate$checks
While @Error = 0
   $dirfile = "%temp%\dirlist.xxx"
   If Exist ("$dirfile")
      Del "$dirfile"
   Endif
   $dirhandle = FreeFileHandle ()
   Shell '%comspec% /c dir $directory /b /o:d > $dirfile'
   If Open ($dirhandle$dirfile) = 0
      $line = ReadLine ($dirhandle)
      If Len ("$line") > 0
         $file = $line
      Endif
      While @Error = 0
         $line = ReadLine ($dirhandle)
         If Len ("$line") > 0
            $file = $line
            Endif
      Loop
      $filedate = GetFileTime ("$directory$file")
      $null = Close ($dirhandle)
      Del "$dirfile"
   Else
      $null = messagebox ("There was an error getting dir of "+$directory,"Error !!",0)
      Exit 1
   Endif
   If $newfile <$file or $newfiledate <$filedate
      If $file <"" and $filedate <""
         $newfile = $file
         $newfiledate = GetFileTime ("$directory$newfile")
         If $checks > 0
            $null = messagebox ("There is a new file in the '$directory'
folder"
+@CRLF+"$newfile -- $newfiledate","New File !!",0)
         Endif
      Endif
   Endif
   $checks = $checks+1
   Sleep 15
Loop



[ 07. October 2003, 23:55: Message edited by: CitrixMan ]

Top
#76989 - 2003-10-08 12:27 AM Re: Detect New File Presence
Richie19Rich77 Offline
Seasoned Scripter
*****

Registered: 2002-08-16
Posts: 624
Loc: London, England
Just doing some quick thinking and a start maybe something like this, then wrap your code around it.

Shane it is a good idea, I like the fact you can monitor a file, can be used for update of patches. A server waiting for a request from a workstation, once it has a request it will send down the patch.



Break On
Call 'd:\kix\functions\dirlist()'

$directory = "C:\ScannedDocs"

$dirlist = DIRLIST($Directory+'\*.*',1+2)
$FileCount = Ubound($dirlist) + 1

While @Error = 0
   
    $Current = $FileCount 
    $dirlist = DIRLIST($Directory+'\*.*',1+2)
    $FileCount = Ubound($dirlist) + 1
   
    Select
   
    Case $FileCount > $Current
        $Count = Val(Ubound($dirlist)) + 1
        ? 'File Added. Number of File(s): '+$Count
   
    Case $FileCount < $Current
        $Count = Val(Ubound($dirlist)) + 1
        ? 'File Deleted. Number of File(s): '+$Count

    EndSelect
Loop



[ 08. October 2003, 00:29: Message edited by: Richard Farthing ]

Top
#76990 - 2003-10-08 12:34 AM Re: Detect New File Presence
Richie19Rich77 Offline
Seasoned Scripter
*****

Registered: 2002-08-16
Posts: 624
Loc: London, England
Another thought, put Dirlist into an Array, and then compare the new array with old array giveing the change and the file name.

Will try and put something together.

Top
#76991 - 2003-10-08 01:24 AM Re: Detect New File Presence
Richie19Rich77 Offline
Seasoned Scripter
*****

Registered: 2002-08-16
Posts: 624
Loc: London, England
Here we go abit rough at the edges but it seems to work.



;Script:        Detect New File Presence
;Author:        Richard Farthing@nhs.net
;Company:       Queen Elizabeth Hospital NHS Trust
;Date:          08/10/03
;Requirements:  DirList Function

;Problems:      When the message box appears telling the user that a
;               new file has been created, it stops the script,
;               so any new files added between clicking on OK will not be detected.
;***************************************************************************************

Break On

;Directory that you want to scan.
$Directory = "C:\ScannedDocs"

;KiX Function DirList() Location
Call 'D:\KiX\Functions\DirList()'

;Checking that scan directory exists
If NOT Exist ($Directory)
    $null = MessageBox ("Error reading directory path","Error: "+@ERROR,0)
    Exit 1
EndIf

$DirList = DIRLIST($Directory+'\*.*',1+2)
$FileCount = Ubound($dirlist) + 1
$Currentdirlist = DIRLIST($Directory+'\*.*',1)

While @Error = 0
    ;Checking that scan directory exists within the loop
    If NOT Exist ($Directory)
        $null = MessageBox ("Error reading directory path","Error: "+@ERROR,0)
        Exit 1
    EndIf   
   
    $Current = $FileCount 
    $dirlist = DIRLIST($Directory+'\*.*',1)
    $FileCount = Ubound($dirlist) + 1
   
    Select
   
    ;Case statement for new files
    Case $FileCount > $Current
        $Count = Val(Ubound($dirlist)) + 1
        ? 'File Added. Number of File(s): '+$Count
        For Each $File In $dirlist
            If AScan($Currentdirlist,$File) = "-1"
                $newfiledate = GetFileTime ("$directory\$File")       
                $null = MessageBox ("There is a new file in the '$directory' folder"+@CRLF+"'$File' -- '$newfiledate'","New File !!",0)
            EndIf
        Next
   
    ;Case statement for deleted files
    Case $FileCount < $Current
        $Count = Val(Ubound($dirlist)) + 1
        ? 'File Deleted. Number of File(s): '+$Count

    EndSelect
   
    $Currentdirlist = DIRLIST($Directory+'\*.*',1)       
    Sleep 2
Loop
;***************************************************************************************




[ 08. October 2003, 01:49: Message edited by: Richard Farthing ]

Top
#76992 - 2003-10-08 01:46 AM Re: Detect New File Presence
Chris S. Offline
MM club member
*****

Registered: 2002-03-18
Posts: 2368
Loc: Earth
Here's a WMI method for monitoring for a new file creation...



Break On

$nul = SetOption("WrapAtEOL","On")

$strComputer = "."

$objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" +
    $strComputer + "\root\cimv2")
@ERROR " " @SERROR ?
   
$colMonitoredEvents = $objWMIService.ExecNotificationQuery 
    ("SELECT * FROM __InstanceCreationEvent WITHIN 10 WHERE " +
    "Targetinstance ISA 'CIM_DirectoryContainsFile' and " +
    "TargetInstance.GroupComponent= " +
    "'Win32_Directory.Name="+'"'+"e:\\\\scripts"+'"'+"'")

@ERROR " " @SERROR ?

Do
    $objLatestEvent = $colMonitoredEvents.NextEvent
    $objLatestEvent.TargetInstance.PartComponent ?
    "Continue monitoring?" Get $ ??
    If $ <"y" Quit() EndIf
Until @ERROR


Top
#76993 - 2003-10-08 04:14 AM Re: Detect New File Presence
Chris S. Offline
MM club member
*****

Registered: 2002-03-18
Posts: 2368
Loc: Earth
Turned the above script into a function.

Action: Pauses script until a new file appears in the target directory.

Returns: Filename



Break On

$nul = SetOption("WrapAtEOL","On")
$nul = SetOption("Explicit","On")

Dim $,$sFile

$sFile = fnFileCreationMon("E:\Scripts")
@ERROR " | " @SERROR ?

$sFile ?

Get $

Function fnFileCreationMon($sFolderOptional $sComputerOptional $lWithin)
    If Not Exist($sFolderExit(3EndIf
    If Not $sComputer $sComputer = "." EndIf
    If Not $lWithin $lWithin = 10 EndIf
    If $lWithin < 0 Exit(1EndIf
   
    Dim $objWMI,$colMonEvents,$objEvent
   
    $sFolder = Join(Split($sFolder,"\"),"\\\\")
   
    $objWMI = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" + $sComputer + "\root\cimv2")
    If @ERROR<0 Exit VAL("&"+Right(DecToHex(@ERROR),4)) EndIf
   
    $colMonEvents = $objWMI.ExecNotificationQuery ("SELECT * FROM __InstanceCreationEvent " +
        "WITHIN " + $lWithin + " WHERE Targetinstance ISA 'CIM_DirectoryContainsFile' and " + 
        "TargetInstance.GroupComponent='Win32_Directory.Name=" + '"' + $sFolder + '"' + "'")
    If @ERROR<0 Exit VAL("&"+Right(DecToHex(@ERROR),4)) EndIf
   
    $objEvent = $colMonEvents.NextEvent
    $fnFileCreationMon = Join(Split(Split($objEvent.TargetInstance.PartComponent,'"')[1],"\\"),"\")
EndFunction


Top
#76994 - 2003-10-08 04:25 AM Re: Detect New File Presence
NTDOC Administrator Offline
Administrator
*****

Registered: 2000-07-28
Posts: 11628
Loc: CA
Hey Chris that is [Big Grin]

Just as an FYI please take a look at this posting I did a while back.

http://81.17.37.55/board/ultimatebb.php?ubb=get_topic;f=13;t=000086

Top
#76995 - 2003-10-08 04:41 AM Re: Detect New File Presence
Lonkero Administrator Offline
KiX Master Guru
*****

Registered: 2001-06-05
Posts: 22346
Loc: OK
think this should do:
$dir=@scriptdir+"\release\"
"stop script by pressing any key." ? "looking at:" ? $dir ?
$=0+dir($dir)
do $!=dir $1=getfiletime($dir+$!) if $1>$ $=$1 endif until ""=$!
"newist: " $
$2=$
do
$=0+dir($dir)
do $!=dir $1=getfiletime($dir+$!) if $1>$ $=$1 $_=$! endif until ""=$!
if $>$2 $2=$
? "lo, THERE IS NEW FILE:" $_
endif
sleep 1
until kbhit


ps, had it as 3-liner as promised boys on MSN but decided to split the lines so you could even use it and see what it does.

[ 08. October 2003, 05:41: Message edited by: Lonkero ]
_________________________
!

download KiXnet

Top
#76996 - 2003-10-08 06:16 AM Re: Detect New File Presence
NTDOC Administrator Offline
Administrator
*****

Registered: 2000-07-28
Posts: 11628
Loc: CA
Hmmm. Original code did not function correctly. It did know when 1st new file was added, but did not know or tell after that.

I'll try this new code and post results.

Top
#76997 - 2003-10-08 06:22 AM Re: Detect New File Presence
NTDOC Administrator Offline
Administrator
*****

Registered: 2000-07-28
Posts: 11628
Loc: CA
New code produces this result

ERROR : Error in expression.!
Script: C:\SCRIPTS\4.x\AD\fncWatchForNewFiles2.kix
Line : 14

Line 14 is:
sleep 1
Line 13 is:
endif

Top
#76998 - 2003-10-08 06:49 AM Re: Detect New File Presence
Lonkero Administrator Offline
KiX Master Guru
*****

Registered: 2001-06-05
Posts: 22346
Loc: OK
weird.
did some more testing and no.
yet tested again with:
$dir=@scriptdir+"\release\"
"stop script by pressing any key." ? "looking at:" ? $dir ?
$=0+dir($dir)
do $!=dir $1=getfiletime($dir+$!) if $1>$ $=$1 endif until ""=$!
"newist: " $
$2=$
do
$=0+dir($dir)
do $!=dir $1=getfiletime($dir+$!) if $1>$ $=$1 $_=$! endif until ""=$!
if $>$2
$2=$
? "lo, THERE IS NEW FILE:" $_
endif
sleep 1
until kbhit
exit 0

same results.
code works fine with 4.20 and 4.22

[ 08. October 2003, 06:59: Message edited by: Lonkero ]
_________________________
!

download KiXnet

Top
#76999 - 2003-10-08 07:20 AM Re: Detect New File Presence
Lonkero Administrator Offline
KiX Master Guru
*****

Registered: 2001-06-05
Posts: 22346
Loc: OK
doc asked good question in IM:
quote:

what kind of results / speed would it have though if it was watching something like the SYSTEM32 folder with thousand plus files?

so I checked and was ready to write some folder size checking and stuff.
but, checking gave the results I couldn't even imagine.
remember, I have indexing turned off.
first scan took about 30 secs.
then it reported the file and became fast.
stopped the script and restarted and behold, it was fast again.
so, seems kix uses shell-object or similar for dir.
this way explorer will keep "cache" of the folder listing for later use.
obviously, that's only a quess, but the results are a fact.
it's fast even for large folders and the processor usage is quite small even with large folders.
anyway, if you don't need that kinda fast retrieval but you can manage with say "sleep 10", you should use that.
with my laptop during this posting it has taken a minute of processor time already scanning system32 with sleep 1.

so, one should see the best suited setting for the folder size and the load-balancing need in the system.
_________________________
!

download KiXnet

Top
#77000 - 2003-10-08 07:37 AM Re: Detect New File Presence
Lonkero Administrator Offline
KiX Master Guru
*****

Registered: 2001-06-05
Posts: 22346
Loc: OK
k, added easy set interval logics.
doc, I can't understand what the heck is going wrong with your wksta.
all works a charm here.
$dir="%windir%\system32\"	;dir where to check. remember ending slash 
$scanningInterval=30 ;time in seconds to wait between scans

; $NewFile is always set to the new file.
; you can also directly code your execution to "lo" section

"stop script by pressing any key." ? "looking at:" ? $dir ?
$=0+dir($dir)
do $!=dir $1=getfiletime($dir+$!) if $1>$ $=$1 endif until ""=$!
"newist: " $
$2=$
do
$=0+dir($dir)
do $!=dir $1=getfiletime($dir+$!) if $1>$ $=$1 $_=$! endif until ""=$!
if $>$2
$2=$
$NewFile=$_
? "lo, THERE IS NEW FILE:" $_
endif
for $_=1 to $scanningInterval
sleep 1
if kbhit
? ? "you wanna exit?" ? "so be it."
sleep 3
exit 0
endif
next
until 1=0


[ 08. October 2003, 07:42: Message edited by: Lonkero ]
_________________________
!

download KiXnet

Top
#77001 - 2003-10-08 09:08 AM Re: Detect New File Presence
Lonkero Administrator Offline
KiX Master Guru
*****

Registered: 2001-06-05
Posts: 22346
Loc: OK
btw, looked at the problems doc had.
from kixtart-manual:
quote:
Remarks
The information returned represents the time the file was last written to.

getfiletime does not give you creation time, nor does it give accesstime.
the modification time is the only factor this script looks at.

I quess that was not the original goal?
_________________________
!

download KiXnet

Top
#77002 - 2003-10-08 09:30 AM Re: Detect New File Presence
Lonkero Administrator Offline
KiX Master Guru
*****

Registered: 2001-06-05
Posts: 22346
Loc: OK
k, if you look the CREATION time (changes as example when copying) this script will work with that.
the previous one is for MODIFICATION time checking.

$dir=@scriptdir+"\release\"	;dir where to check. remember ending slash  
$scanningInterval=5 ;time in seconds to wait between scans

; $NewFile is always set to the new file.
; you can also directly code your execution to "lo" section

"stop script by pressing any key." ? "looking at:" ? $dir ?
$=0+dir($dir)
do $!=dir $1=FP($dir+$!) if $1>$ $=$1 $_=$! endif until ""=$!
"newist: " $_ " -> " $
$2=$
do
$=0+dir($dir)
do $!=dir $1=FP($dir+$!) if $1>$ $=$1 $_=$! endif until ""=$!
if $>$2
$2=$
$NewFile=$_
? "lo, THERE IS NEW FILE:" $_
endif
for $_=1 to $scanningInterval
sleep 1
if kbhit
? ? "you wanna exit?" ? "so be it."
sleep 3
exit 0
endif
next
until 1=0

;func: FP()
; code ripped from fnGetFileProp by Christopher Shilt (christopher.shilt@relizon.com)
Function FP($)
$FP = CreateObject("Scripting.FileSystemObject")
$FP = $FP.GetFile($).datecreated
EndFunction


[ 08. October 2003, 09:44: Message edited by: Lonkero ]
_________________________
!

download KiXnet

Top
#77003 - 2003-10-08 10:03 AM Re: Detect New File Presence
NTDOC Administrator Offline
Administrator
*****

Registered: 2000-07-28
Posts: 11628
Loc: CA
Thanks Lonk.

I'll check it out more later and let you know.

Top
#77004 - 2003-10-08 11:28 AM Re: Detect New File Presence
Richie19Rich77 Offline
Seasoned Scripter
*****

Registered: 2002-08-16
Posts: 624
Loc: London, England
[Frown] Don't it make you sick, I go to bed thinking I have created a nice small script, then I wake up and lonk had made up a super small script.

And he makes it look so easy. [Big Grin]

Top
#77005 - 2003-10-08 11:43 AM Re: Detect New File Presence
Lonkero Administrator Offline
KiX Master Guru
*****

Registered: 2001-06-05
Posts: 22346
Loc: OK
well well...
that's my task as a basta heir.
but I can assure you, creating is never easy and always involves some pain.
my mouse arm is like burning now.
and instead of the work I should have done (and promised to do) last night, I was playing me-wanna-be-skript-kiddie-too.
_________________________
!

download KiXnet

Top
#77006 - 2003-10-08 02:21 PM Re: Detect New File Presence
Kdyer Offline
KiX Supporter
*****

Registered: 2001-01-03
Posts: 6241
Loc: Tigard, OR
I can quickly see this one going to either the FAQ or UDF section. Cool stuff!

Kent
_________________________
Utilize these resources:
UDFs (Full List)
KiXtart FAQ & How to's

Top
#77007 - 2003-10-08 03:54 PM Re: Detect New File Presence
ShaneEP Moderator Offline
MM club member
*****

Registered: 2002-11-29
Posts: 2127
Loc: Tulsa, OK
Hey Lonk...Great script. I have tried all three of the scripts you posted...All seem to work great. But wouldnt you want to combine both Modify change and Creation change into one? I think the 2nd script works the best.

[ 08. October 2003, 15:57: Message edited by: CitrixMan ]

Top
Page 1 of 2 12>


Moderator:  Glenn Barnas, NTDOC, Arend_, Jochen, Radimus, Allen, ShaneEP, Ruud van Velsen, Mart 
Hop to:
Shout Box

Who's Online
0 registered and 657 anonymous users online.
Newest Members
M_Moore, BeeEm, min_seow, Audio, Hoschi
17883 Registered Users

Generated in 0.078 seconds in which 0.033 seconds were spent on a total of 12 queries. Zlib compression enabled.

Search the board with:
superb Board Search
or try with google:
Google
Web kixtart.org