Powershell Change Watcher仅在目录上触发

时间:2018-10-01 22:08:02

标签: powershell filesystemwatcher

我正在Powershell中构建文件监视脚本。我一直在操作来自https://gallery.technet.microsoft.com/scriptcenter/Powershell-FileSystemWatche-dfd7084b

的代码

一切似乎都正常,但是当我进行一些实际测试时,我注意到更改事件仅在父目录上触发,而不是实际文件本身。以下是我已经挖掘和更新的代码:

$folder = 'C:\extended_attributes\testing\DesignerVistaReorganize' # Enter the root path you want to monitor. 
$filter = '*.*'  # You can enter a wildcard filter here. 

# In the following line, you can change 'IncludeSubdirectories to $true if required.                           
$fsw = New-Object IO.FileSystemWatcher $folder, $filter -Property @{IncludeSubdirectories = $true;NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'} 

# Here, all three events are registerd.  You need only subscribe to events that you need: 

Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -Action { 
    $name        = $Event.SourceEventArgs.Name 
    $changeType  = $Event.SourceEventArgs.ChangeType 
    $timeStamp   = $Event.TimeGenerated 
    $filePath    = -join($folder,"\",$name) | Out-String
    Write-Host "The file '$filePath' was $changeType at $timeStamp" -fore green 
    Out-File -FilePath C:\extended_attributes\testing\outlog.txt -Append -InputObject "The file '$filePath' was $changeType at $timeStamp"} 

Register-ObjectEvent $fsw Deleted -SourceIdentifier FileDeleted -Action { 
    $name        = $Event.SourceEventArgs.Name 
    $changeType  = $Event.SourceEventArgs.ChangeType 
    $timeStamp   = $Event.TimeGenerated 
    $filePath    = -join($folder,"\",$name) | Out-String
    Write-Host "The file '$filePath' was $changeType at $timeStamp" -fore red 
    Out-File -FilePath C:\extended_attributes\testing\outlog.txt -Append -InputObject "The file '$filePath' was $changeType at $timeStamp"} 

Register-ObjectEvent $fsw Changed -SourceIdentifier FileChanged -Action { 
    $name        = $Event.SourceEventArgs.Name 
    $changeType  = $Event.SourceEventArgs.ChangeType 
    $timeStamp   = $Event.TimeGenerated 
    $filePath    = -join($folder,"\",$name) | Out-String
    Write-Host "The file '$filePath' was $changeType at $timeStamp" -fore white 
    Out-File -FilePath c:\scripts\filechange\outlog.txt -Append -InputObject "The file '$filePath' was $changeType at $timeStamp"} 

delete和create事件按预期运行(如下所示):

文件创建:

The file 'C:\extended_attributes\testing\DesignerVistaReorganize\Cart_Warnings\newFile.txt' Created at 10/01/2018 14:55:35
  

文件更改:

The file 'C:\extended_attributes\testing\DesignerVistaReorganize\Cart_Warnings'
     

于10/01/2018 15:01:18更改

文件删除:

The file 'C:\extended_attributes\testing\DesignerVistaReorganize\Cart_Warnings\newFile.txt' Deleted at 10/01/2018 14:56:47

我注意到的另一件事是,更改事件仅在根目录下的第一个文件更改时触发。每当创建或删除文件时,就会触发另外两个事件。以前有人遇到过此问题吗?如果可以,请提供一些解决方法的见解?

解决(虽然不是有效答案)

我尝试了许多不同的尝试,试图使此事件始终如一地触发,但似乎只有一个可行。我有两个用于文件更改事件的脚本。它们几乎完全相同,只是事件完成后彼此调用。关键是不能确保在调用第二个脚本之前通过注销事件来杀死观察者。

脚本1

$folder = 'C:\extended_attributes\testing\DesignerVistaReorganize' # Enter the root path you want to monitor. 
$filter = '*.*'  # You can enter a wildcard filter here. 

# In the following line, you can change 'IncludeSubdirectories to $true if required.                           
$fsw = New-Object IO.FileSystemWatcher $folder, $filter -Property @{IncludeSubdirectories = $true;NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'} 

Register-ObjectEvent $fsw Changed -SourceIdentifier FileChanged -Action { 
        echo "Script 1"
        $name = $Event.SourceEventArgs.Name 
        $changeType = $Event.SourceEventArgs.ChangeType 
        $timeStamp = $Event.TimeGenerated 
        $filePath    = -join($folder,"\",$name) | Out-String
        Unregister-Event FileChanged
        Write-Host "The file '$filePath' was $changeType at $timeStamp" -fore white 
        Out-File -FilePath C:\extended_attributes\testing\outlog.txt -Append -InputObject "The file '$filePath' was $changeType at $timeStamp"
        .\change_watcher_2.ps1
} 

脚本2

$folder = 'C:\extended_attributes\testing\DesignerVistaReorganize' # Enter the root path you want to monitor. 
$filter = '*.*'  # You can enter a wildcard filter here. 

# In the following line, you can change 'IncludeSubdirectories to $true if required.                           
$fsw = New-Object IO.FileSystemWatcher $folder, $filter -Property @{IncludeSubdirectories = $true;NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'} 


Register-ObjectEvent $fsw Changed -SourceIdentifier FileChanged -Action { 
        echo "Script 2"
        $name = $Event.SourceEventArgs.Name 
        $changeType = $Event.SourceEventArgs.ChangeType 
        $timeStamp = $Event.TimeGenerated 
        $filePath    = -join($folder,"\",$name) | Out-String
        Unregister-Event FileChanged
        Write-Host "The file '$filePath' was $changeType at $timeStamp" -fore white 
        Out-File -FilePath C:\extended_attributes\testing\outlog.txt -Append -InputObject "The file '$filePath' was $changeType at $timeStamp"
        .\change_watcher_1.ps1
} 

输出

PS C:\extended_attributes\testing> C:\extended_attributes\testing\change_watcher_1.ps1

Id     Name            PSJobTypeName   State         HasMoreData     Location             Command                  
--     ----            -------------   -----         -----------     --------             -------                  
2      FileChanged                     NotStarted    False                                 ...                     



PS C:\extended_attributes\testing> The file 'C:\extended_attributes\testing\DesignerVistaReorganize\BusinessPrinting
' was Changed at 10/02/2018 10:46:43
The file 'C:\extended_attributes\testing\DesignerVistaReorganize\Editor_Warnings
' was Changed at 10/02/2018 10:47:09
The file 'C:\extended_attributes\testing\DesignerVistaReorganize\Mobile\Mobile_Control_Panel_2015_05_14.dvf
' was Changed at 10/02/2018 10:49:50
The file 'C:\extended_attributes\testing\DesignerVistaReorganize\Mobile
' was Changed at 10/02/2018 10:49:58
The file 'C:\extended_attributes\testing\DesignerVistaReorganize\Mobile\Gradients_Panels_Colors_Menus_2015_03_01.dvf
' was Changed at 10/02/2018 10:51:49
The file 'C:\extended_attributes\testing\DesignerVistaReorganize\Mobile\Tablet_Editor_2015_03_31.dvf
' was Changed at 10/02/2018 10:52:46
The file 'C:\extended_attributes\testing\DesignerVistaReorganize\Mobile
' was Changed at 10/02/2018 10:52:57

我真的希望有一个比这更好的解决方案,因为我可以预见到这种方法会带来许多问题。

1 个答案:

答案 0 :(得分:1)

我找到了比原始问题更新中发布的解决方案更好的解决方案。如果您对EnableRaisingEvents使用属性,如下所示。每当对文件系统进行更改时,都会触发该事件:

$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = 'C:\extended_attributes\testing\DesignerVistaReorganize'
$watcher.IncludeSubdirectories = $true
$watcher.EnableRaisingEvents = $true


$changed = Register-ObjectEvent $watcher "Changed" -Action {
    write-host "Changed: $($eventArgs.FullPath)"
    $creation_time = gi -Path $eventArgs.FullPath    | get-itemproperty | select -ExpandProperty CreationTime | Get-date -Format s
    $file_extension = gi -Path $eventArgs.FullPath   | get-itemproperty | select -ExpandProperty Extension    
    $file_base_name = gi -Path $eventArgs.FullPath   | get-itemproperty | select -ExpandProperty BaseName     
    $last_access_time = gi -Path $eventArgs.FullPath | get-itemproperty | select -ExpandProperty LastAccessTime | Get-date -Format s
    $last_write_time = gi -Path $eventArgs.FullPath  | get-itemproperty | select -ExpandProperty LastWriteTime | Get-date -Format s

    Write-Host "Creation time: $($creation_time)"
    Write-Host "ex: $($file_extension)"
    Write-Host "Name: $($file_base_name)"
    Write-Host "access: $($last_access_time)"
    Write-Host "write: $($last_write_time)"

    $object = New-Object System.Object
    $object | Add-Member -type NoteProperty –Name Extension –Value  $file_extension
    $object | Add-Member -type NoteProperty –Name BaseName –Value $file_base_name
    $object | Add-Member -type NoteProperty –Name Createtime –Value $creation_time
    $object | Add-Member -type NoteProperty –Name Accesstime –Value $last_write_time
    $object | Add-Member -type NoteProperty –Name Writetime –Value $last_access_time

    Write-Host "After Object"

    # Load the module
    Import-Module Mdbc
    # Connect the new collection test.test
    Connect-Mdbc . test test -NewCollection
    # add the objects to the collection
    $object | Add-MdbcData
    # Get all data as custom objects and show them in a table
    Get-MdbcData -As PS | Format-Table -AutoSize | Out-String
}