-->

Power Shell Script to Monitor Folder for File chan

2019-08-17 19:47发布

问题:

Looking for help

I am trying to write a utility that monitors any file change in Folder and print the info on the power shell console

Found lot of help from below question, Thanks to OP and answers in the thread.

Powershell script to run a .bat file when a file is added to a folder

I have a script something like this now

$folder = '\\{Networkname}\Partner1\' # Enter the root path you want to monitor. 
$filter = '*'  # You can enter a wildcard filter here. 

$fsw = New-Object IO.FileSystemWatcher $folder, $filter -Property @{IncludeSubdirectories = $false;NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'}

Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -Action { 
$name = $Event.SourceEventArgs.Name 
$changeType = $Event.SourceEventArgs.ChangeType 
$timeStamp = $Event.TimeGenerated 
Write-Host "The file '$name' was $changeType at $timeStamp" -fore green 
write-host "test"

}

When I execute the above script, I am getting below exception

Register-ObjectEvent : Cannot subscribe to event. A subscriber with source identifier 'FileCreated' already exists.
At C:\Users\sysadmin\Desktop\FileWatcher.ps1:6 char:21
+ Register-ObjectEvent <<<<  $fsw Created -SourceIdentifier FileCreated -Action {
    + CategoryInfo          : InvalidArgument: (System.IO.FileSystemWatcher:FileSystemWatcher) [Register-ObjectEvent],
    ArgumentException
    + FullyQualifiedErrorId : SUBSCRIBER_EXISTS,Microsoft.PowerShell.Commands.RegisterObjectEventCommand

I just started with Powershell as I need a utility that monitors File change in Folder, please let me know if there is anything that's wrong in the above code, I am just trying to print the changed file information on the console.

Any help is highly appreciated

Thanks.

回答1:

There are a couple of problems:

  1. You've run the script twice within the same session so an event-watcher already exists with the same name. Use Get-EventSubscriber to see the registered events within the same PowerShell session.
  2. You need to move the 'FileCreated' event in your Register-ObjectEvent cmdlet to the -EventName parameter.

The -Source-Identifier parameter is used as a kind of name parameter.



回答2:

If you want to re-run the same script, add the following line before the Register-ObjectEvent entry:

Unregister-Event FileCreated -ErrorAction:SilentlyContinue