#region Import Assemblies #---------------------------------------------- [void][Reflection.Assembly]::Load("System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089") [void][Reflection.Assembly]::Load("System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089") [void][Reflection.Assembly]::Load("System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a") [void][Reflection.Assembly]::Load("mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089") [void][Reflection.Assembly]::Load("System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089") [void][Reflection.Assembly]::Load("System.Xml, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089") [void][Reflection.Assembly]::Load("System.DirectoryServices, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a") #endregion Import Assemblies #設置監控路徑 $script:folder="C:\" $form=New-Object System.Windows.Forms.Form $form.FormBorderStyle="Fixed3D" $form.StartPosition = 'CenterScreen' $form.ClientSize="200,80" $form.Text="Monitor" $buttonStart=New-Object System.Windows.Forms.Button $buttonStart.Text="Start Watch" $buttonStart.Location="45,10" $buttonStart.add_click({start-watch}) $buttonStart.Size="100,20" $buttonStop=New-Object System.Windows.Forms.Button $buttonStop.Text="Stop Watch" $buttonStop.Location="45,40" $buttonStop.add_click({stop-watch}) $buttonStop.Size="100,20" $form.Controls.AddRange(@($buttonStart,$buttonStop)) $script:watcher = New-Object System.IO.FileSystemWatcher $folder #開始執行監控 function start-watch{ $NotifyFilters=New-Object System.IO.NotifyFilters #$watcher.NotifyFilter="Size,LastWrite,LastAccess,CreationTime,Security" $watcher.Filter = "*.*" $watcher.InternalBufferSize = 65536 #是否包含子目錄 $watcher.IncludeSubDirectories = $True #是否觸發事件,必須開啓 $watcher.EnableRaisingEvents = $True $watcher.SynchronizingObject = $form $form.Text="Monitoring" $buttonStart.Enabled=$false #建立時觸發 $watcher.add_Created({created}) $watcher.add_Changed({changed}) $watcher.add_Deleted({deleted}) $watcher.add_Renamed({renamed}) } function msg($message){ [Windows.Forms.MessageBox]::Show($message) } # $_.changetype 獲取操做類型 # $_.fullpath 獲取文件絕對路徑 function created(){ #建立文件 #本身編寫處理邏輯 msg($_.fullpath) } function changed(){ #文件信息變動 #本身編寫處理邏輯 msg($_.fullpath) } function deleted(){ #刪除文件 #本身編寫處理邏輯 msg($_.fullpath) } function renamed(){ #名稱變動 #本身編寫處理邏輯 msg($_.fullpath) } #中止監控 function stop-watch{ $watcher.EnableRaisingEvents = $false $form.Text="Monitor" $buttonStart.Enabled=$true } $form.ShowDialog()