I have a small utility function in one PowerShell script:
function Unzip-File{
param(
[Parameter(Mandatory=$true)]
[string]$ZipFile,
[Parameter(Mandatory=$true)]
[string]$Path
)
$shell=New-Object -ComObject shell.application
$zip = $shell.namespace($ZipFile)
$target = $shell.NameSpace($Path)
$target.CopyHere($zip.Items())
}
Am I supposed to clean-up the COM objects within the script? Or is PowerShell smart enough to automatically garbage COM Objects?
I've read Getting Rid of a COM Object (Once and For All) and blindly applied:
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($zip)
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($target)
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($shell)
But I'm not sure if this was needed.
What the correct pattern of using COM objects in local functions?
Remove-Variableto release any other references to the variables and then GC will probably take care of the rest. If your objects have aDispose()method you may want to call that as well (before releasing).