Register-ObjectEvent only working after multiple re-runs

Hello,

I want to monitor a specific folder for new created “Exchange Customer.csv”.

The monitoring works fine and in the console he writes “some text” BUT no Exchange2.csv file is being created.

If I start my script again, it writes 2 or 3 times “some text” in the console.

After having started the script for ± 4 times, it writes 6 times “some text” in the console AND creates the file Exchange2.csv.

Then it’s working all the time until I’m stopping it using:

Get-EventSubscriber | Unregister-Event

What am I doing wrong? :slight_smile:

Here this part of the scipt

#watch folder and execute if new file has been added
$folder = $path
$filter = ‘Exchange Customer.csv’
$watcher = New-Object IO.FileSystemWatcher $folder, $filter

$action =

{

#Get Content, remove first 14lines

Get-Content $file| Select-Object -Skip 14 | Set-Content “$path\Exchange2.csv”

Write-Host “some text”

}

Register-ObjectEvent $watcher ‘Created’ -Action $action

 

Thank you

Regards

What is $file?

$path = “P:\Testing”
$filename = ‘Exchange Customer.csv’
$file="$path$filename"

Here a new test:


$PathToMonitor = "P:\Testing"

#    Unregister-Event -SourceIdentifier FSCreate
#    $handler | Remove-Job
#    $FileSystemWatcher.EnableRaisingEvents = $false
#    $FileSystemWatcher.Dispose()
#    "Event Handler disabled."

explorer $PathToMonitor

$FileSystemWatcher = New-Object System.IO.FileSystemWatcher
$FileSystemWatcher.Path  = $PathToMonitor
$FileSystemWatcher.IncludeSubdirectories = $false
$FileSystemWatcher.Filter= 'Exchange Customer.csv'

$FileSystemWatcher.EnableRaisingEvents = $true

$Action = {
    $details = $event.SourceEventArgs
    $Name = $details.Name
    $FullPath = $details.FullPath
    $OldFullPath = $details.OldFullPath
    $OldName = $details.OldName
    $ChangeType = $details.ChangeType
    $Timestamp = $event.TimeGenerated
    $text = "{0} was {1} at {2}" -f $FullPath, $ChangeType, $Timestamp
    Write-Host ""
    Write-Host $text -ForegroundColor Green

    Get-Content "P:\Testing\Exchange Customer.csv" | Select-Object -Skip 14 | Set-Content "P:\Testing\Exchange2.csv"
        
    Write-Host "text"

    }

$handler = . {
    
    Register-ObjectEvent -InputObject $FileSystemWatcher -EventName Created -Action $Action -SourceIdentifier FSCreate

}

Write-Host "Watching for changes to $PathToMonitor"

After running this scipt, a new .csv file is created, but only 3 times. Afterwards is just writes “text” to the console, but “Get-Content “P:\Testing\Exchange Customer.csv” | Select-Object -Skip 14 | Set-Content “P:\Testing\Exchange2.csv”” isn’t executed …