Search code examples
powershell

How to set PowerShell OutputType for a list of named properties


Consider this function which returns a table of string values, each row having two string properties with names DisplayName and DisplayVersion:

function Get-InstalledDotNetPacks{
  [CmdletBinding()]
  Param()
  Get-ItemProperty `
      -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*", `
            "HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*" |
       Where {$_.DisplayName -like '*.NET*'} |
       Select-Object DisplayName, DisplayVersion |
       Sort -Property DisplayName
}

What can I do with OutType() to reveal the two property names that the function will return?


Solution

  • Easiest way would be to define a class that serves as a property bag and allows discovery of those two properties:

    class DotNetPack {
        [string] $DisplayName
        [string] $DisplayVersion
    }
    

    Then you get rid of Select-Object, cause that one returns PSCustomObject, and replace it with instances of your class instead:

    function Get-InstalledDotNetPacks {
        [OutputType([DotNetPack])]
        [CmdletBinding()]
        param(
            [ValidateNotNullOrEmpty()]
            [string[]] $Path = @(
                'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*'
                'HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*'
            )
        )
    
        Get-ItemProperty -Path $Path |
            Where-Object { $_.DisplayName -like '*.NET*' } |
            Sort-Object -Property DisplayName |
            ForEach-Object {
                [DotNetPack]@{
                    DisplayName    = $_.DisplayName
                    DisplayVersion = $_.DisplayVersion
                }
            }
    }
    

    And completion works fine after:

    wow!