Private/GetType.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
using namespace System.Management.Automation

function GetType {
    <#
    .SYNOPSIS
        Get a type info object for any nonpublic or public type.
    .DESCRIPTION
        Retrieve type info directly from the assembly if nonpublic or from implicitly casting if public.
    .INPUTS
        System.String
 
        You can pass type names to this function.
    .OUTPUTS
        System.Type
 
        Returns a Type object if a match is found.
    .EXAMPLE
        PS C:\> 'System.Management.Automation.SessionStateScope' | GetType
        Returns a Type object for SessionStateScope.
    #>

    [CmdletBinding()]
    param (
        # Specifies the type name to search for.
        [Parameter(Mandatory, ValueFromPipeline)]
        [ValidateNotNullOrEmpty()]
        [string]
        $TypeName
    )
    process {
        $type = $TypeName -as [type]

        if (-not $type) {
            $type = [AppDomain]::CurrentDomain.
                GetAssemblies().
                ForEach{ $PSItem.GetType($TypeName, $false, $true) }.
                Where{ $PSItem }[0]
        }

        if (-not $type) {
            $type = [AppDomain]::CurrentDomain.
                GetAssemblies().
                GetTypes().
                Where{ $PSItem.ToString() -match "$TypeName$" }[0]
        }
        # TODO: Pull using statements from the ast to catch some edge cases.
        if (-not $type) {
            ThrowError -Exception ([RuntimeException]::new($Strings.TypeNotFound -f $TypeName)) `
                       -Id        TypeNotFound `
                       -Category  InvalidOperation `
                       -Target    $TypeName
        }
        $type
    }
}