10

I am trying to dispose XmlWriter object:

try
{
    [System.Xml.XmlWriter] $writer = [System.Xml.XmlWriter]::Create('c:\some.xml')
}
finally
{
    $writer.Dispose()
}

Error:

Method invocation failed because [System.Xml.XmlWellFormedWriter] doesn't contain a method named 'Dispose'.

On the other side:

 $writer -is [IDisposable]
 # True

What should I do?

alex2k8
  • 42,496
  • 57
  • 170
  • 221

2 Answers2

11

Dispose is protected on System.Xml.XmlWriter. You should use Close instead.

$writer.Close
Michael
  • 54,279
  • 5
  • 125
  • 144
  • Having a protected method, how can I call it in PowerShell? Type cast does not work '($writer -as [IDisposable]).Dispose()'. Should I use .Net Reflection API?? – alex2k8 Apr 14 '09 at 01:18
  • Call Close instead of Dispose. Close releases all resources. – Michael Apr 14 '09 at 01:19
  • You're talking about the "wrong" `Dispose`. The [`Dispose` he wants](http://msdn.microsoft.com/en-us/library/bb357166.aspx) is not `protected`; it is an explicit interface implementation! Explicit interface implementations are hard to call from PowerShell. But this *hack* should work: `[IDisposable].GetMethod("Dispose").Invoke($writer, @())`. – Jeppe Stig Nielsen Oct 08 '13 at 14:46
8

Here is an alternative approach:

(get-interface $obj ([IDisposable])).Dispose()

Get-Interface script can be found here http://www.nivot.org/2009/03/28/PowerShell20CTP3ModulesInPracticeClosures.aspx and was suggested in this response.

With 'using' keyword we get:

$MY_DIR = Split-Path -Path $MyInvocation.MyCommand.Definition -Parent

# http://www.nivot.org/2009/03/28/PowerShell20CTP3ModulesInPracticeClosures.aspx
. ($MY_DIR + '\get-interface.ps1')

# A bit modified code from http://blogs.msdn.com/powershell/archive/2009/03/12/reserving-keywords.aspx
function using
{
    param($obj, [scriptblock]$sb)

    try {
        & $sb
    } finally {
        if ($obj -is [IDisposable]) {
            (get-interface $obj ([IDisposable])).Dispose()
        }
    }
}

# Demo
using($writer = [System.Xml.XmlWriter]::Create('c:\some.xml')) {

}
Community
  • 1
  • 1
alex2k8
  • 42,496
  • 57
  • 170
  • 221
  • using 'using' in powershell 2.0 i get: The 'using' keyword is not supported in this version of the language. At line:1 char:6 + using <<<< + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : ReservedKeywordNotAllowed – oɔɯǝɹ Sep 07 '10 at 08:21
  • Do you mean that the sample is not working on 2.0. Or it's your own code fails - if so, notice that I had to defined the 'using' keyword in sample above by myself. – alex2k8 Sep 08 '10 at 14:45