Implement System.IDisposable

Just venturing into creating classes in Powershell and have had a little experience of this in C# as a hobbyist developing the odd work tool.

I have a class that opens a COM object and I want to make sure that it is properly disposed of in a destructer (which I don’t think Powershell classes support?) or implementing iDisposable. Is this possible? I’m having trouble getting it to work.


I have now managed to resolve this thankfully. My implementation of IDisposable was correct but I made the wrongful assumption that dispose would get automatically run on all objects at the end of the script by the garbage collector and in a reasonable time. This isn’t the case and you need to wrap your code with a using-object block (similar to C#'s USING statement) or manually call the dispose methods. Using-object is better as it runs dispose even after an exception.

For those that need to achieve the same:

#Define class inherited from IDisposable
Class MyClass: System.IDisposable { }
#Create Dispose Methods
[void] Dispose()
        $this.Disposing = $true

    [void] Dispose([bool]$disposing)
            #Example of releasing an unmanaged com object
#Example using block
Using-Object ($myInstance = New-Object -TypeName MyClass) { $myInstance.DisplayHelloWorld() }