2017-07-24 65 views
0

我想在所有取消註冊任何自定義Register-ObjectEvent的代碼之前運行命令;有些命令與對象事件的Remove-Jobs *類似。我想這樣做,因爲如果我嘗試兩次註冊$watcher,它會引發錯誤。有沒有叫Get-ObjectEvent命令,否則我就不會問這個取消註冊所有自定義對象事件

$folder = "C:\some\path\to\folder" 

# File it is watching 
$filter = "flag.txt" 

# Instantiate Watcher 
$Watcher = New-Object IO.FileSystemWatcher $folder, $filter -Property @{ 
    IncludeSubdirectories = $false 
    NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite' 
} 

# EVENT: $filter is created 
$onCreated = Register-ObjectEvent $Watcher Created -SourceIdentifier FileCreated -Action { 
    $path = $Event.SourceEventArgs.FullPath 
    $name = $Event.SourceEventArgs.Name 
    $changeType = $Event.SourceEventArgs.ChangeType 
    $timeStamp = $Event.TimeGenerated 
    Write-Host "The file '$name' was $changeType at $timeStamp" 
    Write-Host $path 
} 

回答

2

雖然有可能不是一個Get-ObjectEvent一個Get-EventSubscriber

Get-EventSubscriber | Unregister-Event 

此外,事件訂閱是流程本地的,因此終止PowerShell流程也會刪除其中的訂閱。

+0

太棒了!這正是我所期待的 –