Register-ObjectEvent cmdlet not working properly on Powershell but working on ISE

I am working on a Powershell Script to monitor a folder and when a new item is created the script needs to copy that file to another folder.

The issue I’m experiencing is that when I execute it in Powershell ISE it works perfectly but when executing it on Powershell it only works for the period of time that Powershell window is open (> 1 second).

I tried putting the sleep command at the end, and found that only when the script got ended the action is taken, in this case, when I press CTRL+C to stop the script in Powershell, the actions that should have been taken when I created the items are executed all together.

Don’t know if I am doing something wrong or just misunderstanding something.

Here is the script i am using to test it:

$Watcher = New-Object System.IO.FileSystemWatcher
$Watcher.path = "\\192.168.5.127\data\TestWatcher"
$Destination = "C:\TestWatcher"
$Watcher | Get-Member -MemberType Event
$Watcher.EnableRaisingEvents = $true

$action = {
    $path = $event.SourceEventArgs.FullPath
    $name = $event.SourceEventArgs.Name
    $changetype = $event.SourceEventArgs.ChangeType
    Write-Host "File $name at path $path was $changetype at $(get-date)"
    Copy-Item $Watcher.path $Destination
}

Register-ObjectEvent $Watcher 'Created' -Action $action

Any help or advice would be appreciated.

Best Regards,

Frank,
Welcome to the forum. :wave:t4:

When you crosspost the same question at the same time to different forums you should at least post links to the other forums along with your question to avoid people willing to help you making their work twice or more.

Thanks

1 Like