Private/Add-ObjectTypeName.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
Function Add-ObjectTypeName {
<#
    .SYNOPSIS
        Decorates a custom object with a custom type name
    .DESCRIPTION
        Helper function to decorate a custom object with a type name to apply things like formats to it.

        It is a good idea to provide a type name to some of your object to apply custom formatting or result tests to them.

    .PARAMETER InputObject
        Object to decorate with a custom type name. This paramter also accepts pipeline input.

    .PARAMETER TypeName
        This is the type name yout want to insert into your custom object
        This will show up when you use Get-Member against the resulting object.

    .PARAMETER Passthru
        Whether to pass the resulting object through. The default value is $true.

    .EXAMPLE
        # Create an object to work with
        $Object = [PSCustomObject]@{
            First = 'Cookie'
            Last = 'Monster'
            Account = 'CMonster'
        }

        #Add a type name
        Add-ObjectTypeName -InputObject $Object -TypeName 'ApplicationX.Account'

            # First Last Account
            # ----- ---- -------
            # Cookie Monster CMonster

        #Verify that Get-Member shows us the right type
        $Object | Get-Member
            # TypeName: ApplicationX.Account ...

    .NOTES
        Initial code borrowed from Warren Frame - thanks for the great work!
        https://github.com/RamblingCookieMonster

    .LINK
        http://ramblingcookiemonster.github.io/Decorating-Objects/

    .FUNCTIONALITY
        PowerShell Language
    #>


    [CmdletBinding()]
    Param (
        [Parameter( Mandatory=$True,
                    Position=0,
                    ValueFromPipeline=$True )]
        [ValidateNotNullOrEmpty()]
        [PsObject[]]$InputObject,

        [Parameter( Mandatory=$True,
                    Position=1)]
        [String]$TypeName,

        [Boolean]$Passthru = $True
    )

    Process {
        ForEach ($Object in $InputObject) {
            [Void]$Object.PsObject.TypeNames.Insert(0,$TypeName)
        }

        If ($Passthru) {
            $Object
        }
    }
}