Problem with FileSystemWatcher using Loop in Powershell RRS feed

  • Question

  • I used array loops before doing numbered loops (below) and came up with the same issues using FileSystemWatcher.

    When I run this, I get 12 instances of FSW, each looking in 2 directories, 2 file types, 3 event types. The problem I'm having is that when I throw an "index.txt" file into WebSite1, I get the log file:

    File: default.* in E:\websites\WebSite2 Created at 08/30/2017 15:32:36

    Nice that it saw the event, but it is the wrong file type and folder being logged.

    $sDir = @("E:\websites\WebSite1","E:\websites\WebSite2")
    $sName = @("MainSite","SecondSite")
    $fType = @("index.*","default.*")
    $fName = @("Index","Default")
    $eName = @("Created","Deleted","Renamed")
    For ($i=0; $i -le 1; $i++) {
        For ($j=0; $j -le 1; $j++) {
            For ($k=0; $k -le 2; $k++) {
                $sD = $sDir[$i]
                $sN = $sName[$i]
                $fT = $fType[$j]
                $fN = $fName[$j]
                $eN = $eName[$k]
                $SourceID = "$sN$fN$eN"
    #            Add-Content E:\look\logs\outlog.txt "$SourceID"
    $FSW = New-Object IO.FileSystemWatcher $sD, $fT -Property @{IncludeSubdirectories = $false;NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite, DirectoryName'}
    Register-ObjectEvent $FSW $eN -SourceIdentifier $sourceID -Action {
        $name = $Event.SourceEventArgs.Name
        $changeType = $Event.SourceEventArgs.ChangeType
        $timeStamp = $Event.TimeGenerated
        $fullPath = $Event.SourceEventArgs.FullPath
        If ($changeType -eq 'Renamed') {
            $toLog = "File: $fT in $sD $ChangeType to '$fullPath' at $timeStamp"
            }  Else {
            $toLog = "File: $fT in $sD $ChangeType at $timeStamp"
        Add-Content E:\look\logs\outlog.txt $toLog
        $sendTxt = cmd /C wscript E:\look\txtMsg\email.vbs $toLog
        invoke-item $sendTxt

    Jeff Roller

    Wednesday, August 30, 2017 7:49 PM


  • You cannot use this in a loop.  Once started it runs by itself.

    What you are trying to do cannot be done with the FSW.


    Wednesday, August 30, 2017 9:48 PM