フォルダーを監視し、特定の条件に一致するファイルを移動したいので、FileSystemWatcher を使用しようとしています。
新しいファイルごとに呼び出される関数があります。
function ProcessFile()
{
param ([string]$filename)
Write-Host "Processing file '$filename' to $destination"
}
次に、FSW をセットアップします。
Write-Host "Watching $source for new files..."
$fsw = New-Object IO.FileSystemWatcher $source, $filter -Property @{IncludeSubdirectories = $false; NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'}
Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -Action
{
ProcessFile $Event.SourceEventArgs.FullPath
}
ISE から実行すると問題なく動作し、監視フォルダーにドロップしたファイルは正しく追跡されますが、PowerShell ウィンドウを起動して .\FileWatch.ps1 でスクリプトを実行すると、何も起こりません。
「監視中...」メッセージは表示されるが、「処理中...」メッセージは表示されない
これは、ISE では機能するがシェルでは機能しない完全なスクリプトです...
$source = 'D:\Dev\PowerShell\FileWatch\Test\Source'
$filter = '*.*'
$destination = 'D:\Dev\PowerShell\FileWatch\Test\Found\'
function ProcessFile()
{
param ([string]$filename)
Write-Host "Processing file '$filename' to $destination"
}
Write-Host "Watching $source for new files..."
$fsw = New-Object IO.FileSystemWatcher $source, $filter -Property @{IncludeSubdirectories = $false; NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'}
Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -Action {
ProcessFile $Event.SourceEventArgs.FullPath
}