我有一个FileSystemWatcher
脚本,它为每个匹配正则表达式的子文件夹创建一个FileSystemWatcher
。这就像一个魅力。这是我的剧本
$Folders = gci $Dir -Dir | ? Name -match '^\d{5}$' | % {
$source = $_.FullName
$watcher = [System.IO.FileSystemWatcher]::new()
$watcher.IncludeSubdirectories = $false
$watcher.Path = $source
$watcher.Filter = "*.csv"
$watcher.EnableRaisingEvents = $true
New-Variable -Name $_.Name -Value $watcher
}
$action = { stuff }
Get-Variable | ? Name -match '^\d{5}$' | % {
Register-ObjectEvent $_.Value Created -Action $action -SourceIdentifier $_.Name > $null
}
这让我有一些不同变量的FileSystemWatchers,如$70447
,$78900
,$13450
等。
但我在$watcher
也有一个观察者,但这个变量只用于将我的FileSystemWatcher Object
传递给“生产性”的5位变量
我想在$watcher
命令之后做一个$watcher.dispose()
摆脱New-Variable
。但是当我这样做时,我的所有观察者都会抛出错误。
为什么会这样?由于对象已经传递给新变量,因此$watcher
不再使用。有人可以解释一下吗?
谢谢!
编辑:
Register-ObjectEvent : Cannot access thrown Object.
Objektname: "FileSystemWatcher".
In Z:\Powershell-Scripts\FSW.ps1:43 Zeichen:5
+ Register-ObjectEvent $_.Value Created -Action $action -SourceIden ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.IO.FileSystemWatcher:FileSystemWatcher) [Register-ObjectEvent], ObjectDisposedException
+ FullyQualifiedErrorId : INVALID_REGISTRATION,Microsoft.PowerShell.Commands.RegisterObjectEventCommand
如果我不得不猜测,引用会以某种方式与变量绑定,并且处理会导致某种范围问题。我无法复制您的问题,但请考虑没有中间变量分配,看看它是否能解决您的问题:
Get-ChildItem -Path $dir -Directory | ? Name -match '^\d{5}$' | % {
New-Variable -Name $_.Name -Value (New-Object -TypeName System.IO.FileSystemWatcher -Property @{
IncludeSubdirectories = $false
Path = $_.FullName
Filter = '*.csv'
EnableRaisingEvents = $true
})
}
$action = { stuff }
Get-Variable | ? Name -match '^\d{5}$' | % {
$null = $_.Value | Register-ObjectEvent -EventName Created -Action $action -SourceIdentifier $_.Name
}