Search code examples
powershellexcel-addins

Find the Path for Excel-addin in Powershell


I need to create a Powershell script that can search for a custom installed Excel-Addin that we created. I then need to get the path of where the Addin exists and then copy a supporting file to that path.

The issue is I do not know the path of where the Addin is installed, it could vary from machine to machine so I need to be able to get the Addin object by name, then retrieve the path of the Addin and then copy a supporting file to that path.

All the examples I have found all use the path+name :

try {
       $Excel = New-Object -ComObject Excel.Application
} catch {
          Write-Error 'Microsoft Excel does not appear to be installed.'
}

try {
      $ExcelAddins = $Excel.Addins
      $AddinInstalled = $ExcelAddins | ? { $_.Name -eq "MyAddinName" } // this doesnt work, needs path

      if (!$AddinInstalled ) {        
        Write-Host ('Add-in "' + $Addin.BaseName + '" Not installed!')
      } else {
         // now get the path and copy supporting file to the path
         ...
         ...
         Write-Host ('Add-in "' + $Addin.BaseName + '" supporting file copied successfully!')
      }
  } finally {
              $Excel.Quit()
  }

The code above does not work because I don't supply the path. Is there a way to get the Addin by name or loop through the Addin and check name until I find the one I need and then get the path so I can copy a supporting file to that path?


Solution

  • $Excel.Addins returns objects with more properties than just the Name, but that Name property is the addins Filename and includes the extension, like .XLL or .XLAM.

    Another property you could probe is the .Title.

    Try

    try {
        $Excel = New-Object -ComObject Excel.Application
    
        $Excel.Visible = $false
        # you may also try Where-Object { $_.Title -match 'MyAddinName' }
        $myAddIn = $Excel.Addins | Where-Object { $_.Name -match 'MyAddinName' }
    
        if ($myAddIn) {
            Write-Host "AddIn '$($myAddIn.Name)' found in '$($myAddIn.Path)'"
            # copy the supporting file to the Addin's path
            Copy-Item -Path 'X:\YourSupportingFile' -Destination $myAddIn.Path
        }
        else {
            Write-Warning "Addin 'MyAddinName' not found"
        }
    }
    catch {
        Write-Warning "Error:`r`n$($_.Exception.Message)"
    }
    finally {
        if ($Excel) {
            # close and cleanup COM object
            $Excel.Quit()
            $null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($Excel)
            [System.GC]::Collect()
            [System.GC]::WaitForPendingFinalizers()
        }
    }
    

    This assumes there is only one addin found with that name..
    Instead of the regex -match operator you could also use -like '*MyAddinName*' which uses wildcars