Tuesday, January 24, 2012

Powershell (v2) - Function: Get-COMObjects

While looking at a post on Technet about saving files from InfoPath I realized I didn't know the COM object name (the easiest way to Office products in Powershell).  I could have just searched the registry, but, instead, decided to find a function that would do it for me.  Keith Hill's (long) one-liner linked in the post below did the trick to list every COM object on the local machine.
Vista - is there any script to get a list of COM Objects in a computer?
I decided to take it one step further and add a -match operator accessible via a -Name parameter.  After tweaking it with my single parameter, it ended up looking like this:
function Get-COMObjects {

  <#

    .AUTHOR Will Steele (wlsteele@gmail.com)
    .DEPENDENCIES n/a
     .DESCRIPTION This script returns the names of all COM objects on the local machine. If a Name parameter is passed, the function performs a -match on the name.
     .EXAMPLE Get-COMObjects
     .EXAMPLE Get-COMObjects -Name Excel
     .EXTERNALHELP None.
     .FORWARDHELPTARGETNAME None.
     .INPUTS System.String
     .LINK  http://learningpcs.blogspot.com/2012/01/powershell-v2-function-get-comobjects.html 
     .NAME Get-COMObjects
     .NOTES None.
     .OUTPUTS System.String
     .PARAMETER Name An optional parameter used to specify a string used for -match comparison.
     .SYNOPSIS List all local machine COM objects.

   #>

  [CmdletBinding()]
    param(
      [Parameter(
        Mandatory = $false,
        Position = 0,
        ValueFromPipeline = $true
      )]
    [String]
    $Name = $null
  )

  if($Name -eq $null) {
    Get-ChildItem -Path HKLM:\Software\Classes -ErrorAction 0 | `
    Where-Object {$_.PSChildName -match '^\w+\.\w+$' -and `
    (Get-ItemProperty "$($_.PSPath)\CLSID" -ErrorAction 0)} | `
    Select-Object PSChildName
  } else {
    Get-ChildItem -Path HKLM:\Software\Classes -ErrorAction 0 | `
    Where-Object {$_.PSChildName -match '^\w+\.\w+$' -and `
    (Get-ItemProperty "$($_.PSPath)\CLSID" -ErrorAction 0)} | `
    Where-Object {$_.PSChildName -match $Name} | `
    Select-Object PSChildName
  }
}

0 comments:

Post a Comment