3

I want to monitor a folder and move files that match certain criteria, so I'm trying to use the FileSystemWatcher.

I have a function that will be called with each new file:

function ProcessFile()
{
    param ([string]$filename)
    Write-Host "Processing file '$filename' to $destination"
}

And then I set up a 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 
}

That works fine when I run it from the ISE, and any files I drop into the watched folder are correctly tracked, but if I start a PowerShell window and run the script with .\FileWatch.ps1 then nothing happens.

I see the "watching ..." message, but never see a "processing..." message

Here's the full script that works in the ISE but not in a shell...

$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

The problem is that your function ProcessFile isn't loaded in powershell session.

Try loading you script in this way:

. .\myscript.ps1

In this way your code in my system works!

Read about Dot Sourcing a script in powershell.

于 2012-10-12T13:45:55.967 回答