How to prevent recursion in powerEvents event scripts

When registering a powerEvents event For example an AddFile event and adding a file to Vault inside of the event, the event will be executed an infinite amount of times because adding the file inside of the event triggers the event again.

Avoid recursion in powerEvents

To avoid this issue you can temporarily unregister the registered event using Unregister-VaultEvent, add the file to Vault and then register the event again using Register-VaultEvent.

The Register-VaultEvent Cmdlet automatically generates a SoureIdentifier GUID to identify the registered event.

It is important to pass the SourceIdentifier parameter to the Unregister-VaultEvent Cmdlet and the Register-VaultEvent Cmdlet that registers the event again to avoid double event registration. This parameter ensures that the same event is registered and unregistered:

Import-Module powerEvents
$addFileEvent = Register-VaultEvent -EventName AddFile_Post -Action 'PostAddFile'

function PostAddFile($file, $parentFolder, $dependencies, $attachments, $fileBom, $successful) {
Unregister-VaultEvent -EventName $addFileEvent.Name -SourceIdentifier $addFileEvent.SourceIdentifier
$newFile = Add-VaultFile -From "C:\Temp\Drawing.idw" -To "$/Designs/Inventor/Drawing.idw"
$addFileEvent = Register-VaultEvent -EventName $addFileEvent.Name -Action $addFileEvent.Command -SourceIdentifier
$addFileEvent.SourceIdentifier
}
 

See Also