FileSystemWatcher works in the PowerShell ISE but not when run

房东的猫 提交于 2019-12-23 20:29:56

问题


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 
}

回答1:


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.



来源:https://stackoverflow.com/questions/12860169/filesystemwatcher-works-in-the-powershell-ise-but-not-when-run

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!