Best way to check if an PowerShell Object exist?

前端 未结 7 2029
无人及你
无人及你 2020-12-10 10:19

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         


        
相关标签:
7条回答
  • 2020-12-10 10:55

    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:

    • RCW & reference counting when using COM interop in C#
    • RCW Reference Counting Rules != COM Reference Counting Rules
    • “COM object that has been separated from its underlying RCW cannot be used” with .NET 4.0

    and some other cool things to know:

    • COM object that has been separated from its underlying RCW cannot be used
    • Custom Marshaling
    • Advanced COM Interoperability
    0 讨论(0)
提交回复
热议问题