Last active
November 29, 2022 07:01
-
-
Save stknohg/e01e4b2436e28b24fa39 to your computer and use it in GitHub Desktop.
FileSystemWatcherを使ってファイルの変更監視する簡単なファンクション。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<# | |
.Synopsis | |
指定したパスにあるファイルの変更を監視します。 | |
.DESCRIPTION | |
指定したパスにあるファイルの変更を監視します。 | |
監視を止める場合はCtrl+Cを押してください。 | |
.PARAMETER Path | |
監視するディレクトリを指定します。 | |
.PARAMETER Filter | |
監視するファイル名(に対するフィルタ)を指定します。 | |
.PARAMETER StartAction | |
監視を開始した際のイベント処理を記述します。 | |
.PARAMETER ChangedAction | |
ファイルの変更を検知した際のイベント処理を記述します。 | |
.PARAMETER EndAction | |
監視を終了した際のイベント処理を記述します。 | |
.EXAMPLE | |
Start-FileWatch -Path "C:\" -Filter "Sample.txt" | |
#> | |
function Start-FileWatch | |
{ | |
[CmdletBinding()] | |
Param | |
( | |
[Parameter(Mandatory=$true)] | |
[ValidateNotNullOrEmpty()] | |
[string]$Path, | |
[Parameter(Mandatory=$true)] | |
[ValidateNotNullOrEmpty()] | |
[string]$Filter, | |
[Parameter(Mandatory=$false)] | |
[ScriptBlock]$StartAction = { | |
Write-Host ("{0:yyyy/MM/dd HH:mm:ss} | Start watching..." -f (Get-Date)) | |
}, | |
[Parameter(Mandatory=$false)] | |
[ScriptBlock]$ChangedAction = { | |
Write-Warning ("{0:yyyy/MM/dd HH:mm:ss} | File [{1}] was changed!" -f (Get-Date), $Event.SourceEventArgs.Name) | |
}, | |
[Parameter(Mandatory=$false)] | |
[ScriptBlock]$EndAction = { | |
Write-Host ("{0:yyyy/MM/dd HH:mm:ss} | Stop watching..." -f (Get-Date)) | |
} | |
) | |
if( -not (Test-Path $Path -PathType Container) ) | |
{ | |
throw "Path : $Path was not found." | |
} | |
try | |
{ | |
$Watcher = New-Object System.IO.FileSystemWatcher | |
$Watcher.Path = $Path | |
$Watcher.Filter = $Filter | |
$Watcher.IncludeSubdirectories = $false | |
$Watcher.NotifyFilter = [IO.NotifyFilters]::LastWrite | |
# start file watching. | |
if( $null -ne $StartAction ) | |
{ | |
$StartAction.Invoke() | |
} | |
# register changed event and wait. | |
$SourceID = "Start-FileWatch_Changed" | |
Register-ObjectEvent $Watcher -EventName "Changed" -SourceIdentifier $SourceID -SupportEvent -Action $ChangedAction | |
Wait-Event -SourceIdentifier $SourceID | |
} | |
finally | |
{ | |
# end watching. | |
if( $null -ne $EndAction ) | |
{ | |
$EndAction.Invoke() | |
} | |
Unregister-Event -SourceIdentifier $SourceID -Force | |
$Watcher.Dispose() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment