Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell - Release ComObject

Tags:

powershell

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()
like image 211
Bandit Avatar asked Sep 17 '25 07:09

Bandit


1 Answers

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

like image 102
Theo Avatar answered Sep 20 '25 00:09

Theo