functions/Export-PSTypeExtension.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
Function Export-PSTypeExtension {
    [cmdletbinding(SupportsShouldProcess, DefaultParameterSetName = "Object")]
    Param(
        [Parameter(
            Position = 0,
            Mandatory,
            HelpMessage = "The type name to export like System.IO.FileInfo",
            ParameterSetName = "Name"
        )]
        [ValidateNotNullOrEmpty()]
        [string]$TypeName,

        [Parameter(
            Mandatory,
            HelpMessage = "The type extension name",
            ParameterSetName = "Name"
        )]
        [ValidateNotNullOrEmpty()]
        [string[]]$MemberName,

        [Parameter(
            Mandatory,
            HelpMessage = "The name of the export file. The extension must be .json,.xml or .ps1xml"
        )]
        [ValidatePattern("\.(xml|json|ps1xml)$")]
        [string]$Path,

        [Parameter(ParameterSetName = "Object", ValueFromPipeline)]
        [object]$InputObject,

        [switch]$Passthru
    )
    DynamicParam {
        #create a dynamic parameter to append to .ps1xml files.
        if ($Path -match '\.ps1xml$') {

            #define a parameter attribute object
            $attributes = New-Object System.Management.Automation.ParameterAttribute
            $attributes.HelpMessage = "Append to an existing .ps1xml file"

            #define a collection for attributes
            $attributeCollection = New-Object -Type System.Collections.ObjectModel.Collection[System.Attribute]
            $attributeCollection.Add($attributes)

            #define the dynamic param
            $dynParam1 = New-Object -Type System.Management.Automation.RuntimeDefinedParameter("Append", [Switch], $attributeCollection)

            #create array of dynamic parameters
            $paramDictionary = New-Object -Type System.Management.Automation.RuntimeDefinedParameterDictionary
            $paramDictionary.Add("Append", $dynParam1)
            #use the array
            return $paramDictionary

        } #if
    } #dynamic parameter

    Begin {
        Write-Verbose "Starting: $($MyInvocation.Mycommand)"
        Write-Verbose "Detected parameter set $($pscmdlet.ParameterSetName)"
        $PathParent = Split-Path -Path $Path

        if (Test-Path -Path $PathParent) {
            $validPath = $true
        }
        else {
            Write-Warning "Can't find parent path $pathParent"
            $validPath = $False
        }

        #test if appending
        if ($append -AND (Test-Path $Path)) {
            $validPath = $true
        }
        elseif ($append) {
            Write-Warning "Can't find $path for appending."
            $validPath = $False
        }

        #initialize a list of objects
        $data = [System.Collections.Generic.list[object]]::new()

        if ($TypeName) {
            Write-Verbose "Converting $typename to properly cased type name."
            $TypeName = _convertTypeName $TypeName
        }
    }
    Process {
        #test if parent path exists
        If ($validPath) {
            if ($Inputobject) {
                Write-Verbose "Processing input type: $($InputObject.TypeName)"

                Write-Verbose "Converting $($InputObject.typename) to properly cased type name."
                $TypeName = _convertTypeName $InputObject.TypeName

                $data.Add($InputObject)
            }
            else {
                Write-Verbose "Processing type: $TypeName"
                foreach ($member in $membername) {
                    $typemember = Get-PSTypeExtension -TypeName $Typename -Members $Member
                    $data.Add($typemember)
                }
            }
        } #test path parent
    }
    End {
        if ($validPath) {
            Write-Verbose "Exporting data to $path"

            if ($Path -match "\.ps1xml$") {

                if ($PSBoundParameters["Append"]) {
                    $cpath = Convert-Path $path
                    Write-Verbose "Appending to $cpath"

                    [xml]$doc = Get-Content $cPath
                    $members = $doc.types.SelectNodes("Type[Name='$typeName']").Members

                    if ($members) {
                        Write-Verbose "Appending to existing typename entry"
                    }
                    else {
                        Write-Verbose "Creating a new typename entry for $TypeName"
                        $main = $doc.CreateNode("element", "Type", $null)
                        $tName = $doc.CreateElement("Name")
                        $tName.InnerText = $typename
                        [void]($main.AppendChild($tname))
                        $members = $doc.CreateNode("element", "Members", $null)
                        $IsNewType = $True
                    }

                    foreach ($extension in $data) {
                        Write-Verbose "Exporting $($extension.membername)"
                        $membertype = $doc.createNode("element", $extension.memberType, $null)
                        $membernameEL = $doc.CreateElement("Name")

                        $membernameEL.innertext = $extension.memberName
                        [void]($membertype.AppendChild($membernameEL))

                        Switch ($extension.Membertype) {
                            "ScriptMethod" {
                                $memberdef = $doc.createelement("Script")
                            }
                            "ScriptProperty" {
                                $memberdef = $doc.createelement("GetScriptBlock")
                            }
                            "AliasProperty" {
                                $memberdef = $doc.createelement("ReferencedMemberName")
                            }
                            "NoteProperty" {
                                $memberdef = $doc.createelement("Value")
                            }
                            Default {
                                Throw "Can't process a type of $($extension.MemberType)"
                            }
                        } #switch membertype

                        $memberdef.InnerText = $extension.value
                        [void]($membertype.AppendChild($memberdef))
                        [void]($members.AppendChild($membertype))

                    } #foreach extension

                    if ($IsnewType) {
                        Write-Verbose "Appending new type"
                        [void]($main.AppendChild($members))
                        [void]($doc.types.AppendChild($main))
                    }

                    if ($PSCmdlet.ShouldProcess($cpath)) {
                        $doc.save($cpath)
                    } #end Whatif

                } #if append

                else {
                    Write-Verbose "Saving as new PS1XML"
                    #create a placeholder file so that I can later convert the path
                    [void](New-Item -Path $path -Force)
                    [xml]$Doc = New-Object System.Xml.XmlDocument

                    #create declaration
                    $dec = $Doc.CreateXmlDeclaration("1.0", "UTF-8", $null)
                    #append to document
                    [void]($doc.AppendChild($dec))

                    #create a comment and append it in one line
                    $text = @"
 
This file was created with Export-PSTypeExtenstion from the
PSTypeExtensionTools module which you can install from
the PowerShell Gallery.
 
Use Update-TypeData to import this file in your PowerShell session.
 
Created $(Get-Date)
 
"@

                    [void]($doc.AppendChild($doc.CreateComment($text)))

                    #create root Node
                    $root = $doc.CreateNode("element", "Types", $null)
                    $main = $doc.CreateNode("element", "Type", $null)
                    $name = $doc.CreateElement("Name")
                    $name.innerText = $data[0].TypeName
                    [void]($main.AppendChild($name))
                    $members = $doc.CreateNode("element", "Members", $null)
                    foreach ($extension in $data) {
                        Write-Verbose "Exporting $($extension.membername)"
                        $membertype = $doc.createNode("element", $extension.memberType, $null)
                        $membernameEL = $doc.CreateElement("Name")

                        $membernameEL.innertext = $extension.memberName
                        [void]($membertype.AppendChild($membernameEL))

                        Switch ($extension.Membertype) {
                            "ScriptMethod" {
                                $memberdef = $doc.createelement("Script")
                            }
                            "ScriptProperty" {
                                $memberdef = $doc.createelement("GetScriptBlock")
                            }
                            "AliasProperty" {
                                $memberdef = $doc.createelement("ReferencedMemberName")
                            }
                            "NoteProperty" {
                                $memberdef = $doc.createelement("Value")
                            }
                            Default {
                                Throw "Can't process a type of $($extension.MemberType)"
                            }
                        }
                        $memberdef.InnerText = $extension.value
                        [void]($membertype.AppendChild($memberdef))
                        [void]($members.AppendChild($membertype))

                    } #foreach extension
                    [void]($main.AppendChild($members))
                    [void]($root.AppendChild($main))
                    [void]($doc.AppendChild($root))
                    $out = Convert-Path $path
                    if ($PSCmdlet.ShouldProcess($out)) {
                        $doc.save($out)
                    } #end Whatif
                } #else
            } #if ps1xml
            elseif ($path -match "\.xml$") {
                Write-Verbose "Saving as XML"
                $data | Export-Clixml -Path $path
            }
            else {
                Write-Verbose "Saving as JSON"
                $data | ConvertTo-Json | Set-Content -Path $Path
            }
        } #if valid path

        if ($Passthru) {
            Get-Item -Path $Path
        }
        Write-Verbose "Ending: $($MyInvocation.Mycommand)"
    }

} #end Export-PSTypeExtension