Garbagecollect funciton error with excel

projectja used Ask the Experts™

I am preparing a script to work with excel sheet. The thing is when I try to use Garbagecollect I get an error.

This is the error message:

Exception calling "ReleaseComObject" with "1" argument(s): "Object reference not set to an instance of an object."
At E:\Preparacion\scripts\CASINO-CGM-pruebas.ps1:522 char:64
+     ([System.Runtime.Interopservices.Marshal]::ReleaseComObject <<<< ([System.__ComObject]$ref) -gt 0)
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

An extact of the script code:
you can see the code below. Line 522 is:
... ReleaseComObject([System.__ComObject]$ref) -gt 0)..


Function GarbageCollect ([object]$ref){
    ([System.Runtime.Interopservices.Marshal]::ReleaseComObject([System.__ComObject]$ref) -gt 0)

 $a = GarbageCollect($c)
 $a = GarbageCollect($Wb)
 $a = GarbageCollect($xl)


Please, I would thank your help. I am absolutelly lost with this issue. I have used that function before, however, I dont sure what is happening in this case
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Full stack Software Engineer
check if $ref passed to the function is not null before calling ReleaseComObject.
Meir RivkinFull stack Software Engineer

why grade C?
did i solve your problem or not?

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial