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.
There are a couple of problems:
Get-EventSubscriber
to see the registered events within the same PowerShell session.FileCreated
' event in yourRegister-ObjectEvent
cmdlet to the-EventName
parameter.The
-Source-Identifier
parameter is used as a kind of name parameter.If you want to re-run the same script, add the following line before the Register-ObjectEvent entry: