Make Register-ObjectEvent Persistent

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"}

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?

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.

Good Point Guys Thanks for the advice