通过简单的方式监听文件的更改

Posted on 2019-04-14 17:42  努力成长静待花开  阅读(437)  评论(0编辑  收藏  举报

效果预览:

  

 实现代码:

$LogFile="$HOME\Desktop\log.txt"
$PathToMonitor="$home\test"
$TimeOut=1000
$FileSystemWatcher=New-Object System.IO.FileSystemWatcher $PathToMonitor
$FileSystemWatcher.IncludeSubdirectories=$true
Write-Host "Monitoring Content of $PathToMonitor"
While($true)
{
    $change=$FileSystemWatcher.WaitForChanged('All',$TimeOut)
    if($change.TimedOut -eq $false)
    {
        ##get information about change detected
        Write-Host "Change Detected:"
        $change|Out-Default
        (Get-Date),$change.ChangeType.ToString(),$change.Name|Out-File $LogFile -Append
    }
    else
    { Write-Host '.' -NoNewline }
}