powershell FileSystemWatcher监控文件变化

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/shrekz/article/details/52873901
[void][System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$folder = "E:\test" #要监控的文件夹
#设置任务栏图标
$Icon = "C:\Windows\winsxs\amd64_microsoft-windows-dxp-deviceexperience_31bf3856ad364e35_6.1.7601.17514_none_a54b31331066c8e2\sync.ico"
$form = new-object System.Windows.Forms.Form 
$ni = new-object System.Windows.Forms.NotifyIcon
$niMenu = new-object System.Windows.Forms.ContextMenu
$watcher = New-Object System.IO.FileSystemWatcher $folder

$ni.Icon = New-object System.Drawing.Icon($Icon)
$ni.ContextMenu = $niMenu

$miExit = new-object System.Windows.Forms.MenuItem
$miExit.Text = "Exit" 
$miExit.Add_Click({Stop-Process -id $pid})

$niMenu.MenuItems.AddRange(@($miExit)) 

$watcher.Filter="*.*"
$watcher.InternalBufferSize=65536
$watcher.IncludeSubDirectories = $true
$watcher.SynchronizingObject = $form 
$form.ShowInTaskbar = $False 
$form.WindowState = "minimized"

function action{param($message)
Write-Host $message 
$message >> e:\filechange.log
} #在这里进行日志操作 


$watcher.NotifyFilter = "FileName,DirectoryName,LastWrite"
$watcher.add_Changed({
$message = "$((get-date).ToShortTimeString()) : $($_.FullPath) $($_.ChangeType)" 
action $message
})
$watcher.add_Created({
$message = "$((get-date).ToShortTimeString()) : $($_.FullPath) $($_.ChangeType)"
action $message
})
$watcher.add_Deleted({
$message = "$((get-date).ToShortTimeString()) : $($_.FullPath) $($_.ChangeType)" 
action $message
})
$watcher.add_Renamed({
$message = "$((get-date).ToShortTimeString()) : $($_.OldFullPath) to $($_.FullPath) $($_.ChangeType)"
action $message
})

$watcher.EnableRaisingEvents = $true
$NI.Visible = $True
$form.showdialog()

猜你喜欢

转载自blog.csdn.net/shrekz/article/details/52873901
今日推荐