Home > Enterprise >  PowerShell - Release ComObject
PowerShell - Release ComObject

Time:06-05

I am creating a new com object to open a popup message

$a = new-object -comobject wscript.shell
$b = $a.popup(“WARNING“,0,”Box title”,0   0x30)

I noticed that the object remained opened all the time. Should I need to release it? The commands below will do the job?

$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($a)
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()

CodePudding user response:

Yes, that is good practice. By releasing the com object, it is marked for cleanup to be destroyed by the garbage collector.

Actually, the reference counter of the object is decreased and if this reaches zero, the object is removed from memory when the garbage collector runs. You cannot control when that happens, but this way you make sure the object gets removed. See here

  • Related