Make Register-ObjectEvent Persistent

This topic contains 3 replies, has 3 voices, and was last updated by Profile photo of H Man H Man 2 years, 3 months ago.

  • Author
  • #23282
    Profile photo of H Man
    H Man

    I am trying to put in place a FileSystemWatcher. The code I am running is working perfectly , however it is only good for the active session.

    is there anyway to make this persistent pass the active session

    heres the code i am using

    $folder = 'c:\scripts\test' 
    $filter = '*.*' 
    $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
    Out-File -FilePath c:\scripts\filechange\outlog.txt -Append -InputObject "The file '$name' was $changeType at $timeStamp"}
  • #23283
    Profile photo of Dave Wyatt
    Dave Wyatt

    With the FileSystemWatcher, no. That object only stays active for as long as the process / AppDomain is running, at the most. You could look into a permanent WMI event consumer, but honestly, all you're doing here is (partially) reinventing the wheel of file system auditing. Why not just enable auditing, and review the Security event log when you want to know what files were changed, and when?

  • #23286
    Profile photo of Don Jones
    Don Jones

    If you need a permanent FileSystemWatcher, you're getting into .NET programming, and making a background service. The whole point of a service is to run persistent code. And as Dave points out, the event log does this already, with less overhead.

  • #23289
    Profile photo of H Man
    H Man

    Good Point Guys Thanks for the advice

You must be logged in to reply to this topic.