Is there a way to detect if an object is already disposed? An an example would be
$Watcher=New-Object -TypeName System.IO.FileSystemWatcher -Property @{
Path="C:\"
Filter="Test.txt"
IncludeSubdirectories=$false
NotifyFilter=[IO.NotifyFilters]::FileName, [IO.NotifyFilters]::LastWrite
}
I checked a few other forums and some came up with this:
$watcher -is [System.IDisposable]
But I believe that only detects if an object has the Dispose method. Does anyone have any ideas?
You would want to put a try/catch block around the code where an object may already be disposed. The catch type should be catch [System.ObjectDisposedException] {...
then reinitialize the object for use.
When I dispose that object, I use:
$Watcher.Dispose()
I wouldn’t get an exception cause the Dispose method’s definition is:
void Dispose()
void IDisposable.Dispose()
I tried it to verify it was gonna work using this:
Try
{
$Watcher.Dispose()
}
Catch [System.ObjectDisposedException] {
"An exception has been caught 1"
}
Catch {
"An exception has been caught 2"
}
My console is blank and do not see any messages.