Make Register-ObjectEvent Persistent

Welcome Forums General PowerShell Q&A Make Register-ObjectEvent Persistent

This topic contains 3 replies, has 3 voices, and was last updated by

 
Participant
3 years, 7 months ago.

  • Author
    Posts
  • #23282

    Participant
    Points: 0
    Rank: Member

    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

    Member
    Points: 0
    Rank: Member

    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

    Keymaster
    Points: 2
    Rank: Member

    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

    Participant
    Points: 0
    Rank: Member

    Good Point Guys Thanks for the advice

The topic ‘Make Register-ObjectEvent Persistent’ is closed to new replies.