Reusing a New Object for OLEDB

I have some processing in a loop. I am tryhing to reuse an object instead of making another one - different name. Does powershell destroy an object if that same object name is rebuilt/reloaded? For example:

$CMcommand = New-Object System.Data.OleDb.OleDbCommand $QeuryCM,$CMconnection 
$CMcommand = New-Object System.Data.OleDb.OleDbCommand $Qeury2,$CMconnection 

thx Mark

Yes, memory management is automatic in PS, you don’t need to release objects in most cases.
Your second assignment will destroy previous object when garbage collector runs.

Thanks metablaster. This helps

You’re welcome, you can read more about it here:
Memory management and patterns in ASP.NET Core | Microsoft Learn

You can also force garbage collector to destroy unused objects with [gc]::Collect() although it’s not needed in most cases.

You might find it useful when using .NET classes which create handles, a handle is released when the .NET object is destroyed but it’s not a golden rule, in some cases you might need to force releasing handles ie. for some operation to succeed.

ex. reg.exe unload won’t succeed unless all handles to manually loaded hive are released, but this are esoteric cases.