I need a way to monitor when a file gets deleted off of the disk -- If the file is not deleted by a particular time, we will know that one of our other processes FAILED -- and we can be alerted, etc.
PowerShell is my tool of choice and I know I can check when the file EXISTS using Test-Path, however -- I would like to use something like LastWriteTime but specifically for that file in that directory.
Also -- if we can ASSUME that the folder can be modified in ANOTHER way (possibly via other unrelated files in the folder) -- I would ideally like to understand if THAT particular file was deleted and WHEN.
If you want recorded when a specific file was deleted, you need a FileSystemWatcher
that monitors the file for deletion and logs the information someplace you can retrieve it later (the eventlog for instance).
Create a new event source (requires admin privileges):
New-EventLog -Source 'FileMonitor' -LogName 'Application'
Then create the actual monitor (code shamelessly stolen from here):
$folder = 'c:\some\folder'
$file = 'something.txt'
$fsw = New-Object IO.FileSystemWatcher $folder, $file -Property @{
IncludeSubdirectories = $false
NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'
}
Register-ObjectEvent $fsw Deleted -SourceIdentifier FileDeleted -Action {
Write-EventLog -LogName 'Application' -Source 'FileMonitor' -EventId 42 `
-EntryType 'Information' -Message $Event.TimeGenerated
}
The deletion time(s) can then be fetched from the eventlog like this:
Get-EventLog -LogName 'Application' -Source 'FileMonitor' -InstanceId 42 `
-After (Get-Date).AddHours(-5) | % { [DateTime]$_.Message }
The above will retrieve deletion events that occurred within the last 5 hours.
Unregister watched events like this:
Unregister-Event -SourceIdentifier FileDeleted