FileSystemWatcher可在PowerShell ISE中运行,但无法在运行时运行 [英] FileSystemWatcher works in the PowerShell ISE but not when run
问题描述
我想监视一个文件夹并移动符合某些条件的文件,所以我试图使用FileSystemWatcher.
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"
}
然后我设置了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运行脚本,那么什么都不会发生.
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
这里是可在ISE中运行但不在Shell中运行的完整脚本...
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
}
推荐答案
问题是您的函数ProcessFile
未在Powershell会话中加载.
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!
了解有关 Dot Sourcing
Powershell中的脚本.
Read about Dot Sourcing
a script in powershell.
这篇关于FileSystemWatcher可在PowerShell ISE中运行,但无法在运行时运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!