3

フォルダーを監視し、特定の条件に一致するファイルを移動したいので、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 
}
4

1 に答える 1

5

問題は、関数ProcessFileが powershell セッションに読み込まれていないことです。

この方法でスクリプトをロードしてみてください:

. .\myscript.ps1

このようにして、私のシステムのコードが機能します!

Dot SourcingPowerShell のスクリプトについてお読みください。

于 2012-10-12T13:45:55.967 に答える