I am looking for the best way to check if a Com Object exists.
Here is the code that I have; I\'d like to improve the last line:
$ie = New-Object -Co
Incase you you're like me and you landed here trying to find a way to tell if your PowerShell variable is this particular flavor of non-existent:
COM object that has been separated from its underlying RCW cannot be used.
Then here's some code that worked for me:
function Count-RCW([__ComObject]$ComObj){
try{$iuk = [System.Runtime.InteropServices.Marshal]::GetIUnknownForObject($ComObj)}
catch{return 0}
return [System.Runtime.InteropServices.Marshal]::Release($iuk)-1
}
example usage:
if((Count-RCW $ExcelApp) -gt 0){[System.Runtime.InteropServices.Marshal]::FinalReleaseComObject($ExcelApp)}
mashed together from other peoples' better answers:
and some other cool things to know: