获取文件删除时间的脚本

Script to get timestamp of when file was deleted

我需要一种方法来监视文件何时从磁盘中删除 -- 如果文件在特定时间未被删除,我们将知道我们的其他进程之一失败了 -- 我们可以收到警报等

PowerShell 是我选择的工具,我知道我可以使用 Test-Path 检查文件何时存在,但是 - 我想使用类似 LastWriteTime 但专门用于 that 目录中的 that 文件。

此外 - 如果我们可以假设文件夹 可以 以另一种方式修改(可能通过文件夹中的其他不相关文件) - 我想知道是否该特定文件已删除,时间为

如果你想记录何时一个特定的文件被删除,你需要一个FileSystemWatcher来监视文件的删除并将信息记录在某个地方,你可以稍后检索它(例如事件日志)。

创建新事件源(需要管理员权限):

New-EventLog -Source 'FileMonitor' -LogName 'Application'

然后创建实际的监视器(无耻地从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
}

然后可以像这样从事件日志中获取删除时间:

Get-EventLog -LogName 'Application' -Source 'FileMonitor' -InstanceId 42 `
    -After (Get-Date).AddHours(-5) | % { [DateTime]$_.Message }

以上将检索最近 5 小时内发生的删除事件。

注销这样观看的事件:

Unregister-Event -SourceIdentifier FileDeleted