|
| 1 | +function Write-FormatSelectionSet |
| 2 | +{ |
| 3 | + <# |
| 4 | + .SYNOPSIS |
| 5 | + Writes a selection set. |
| 6 | + .DESCRIPTION |
| 7 | + Writes a format selection set. |
| 8 | + .NOTES |
| 9 | + Formatting is commonly selected by a TypeName. |
| 10 | + |
| 11 | + It can also be selected by a group of type names, which is called a SelectionSet. |
| 12 | +
|
| 13 | + A few built-in formatters use selection sets, most notably the filesystem formatters. |
| 14 | + .EXAMPLE |
| 15 | + Write-FormatSelectionSet -Name 'FileSystemTypes' -TypeName 'System.IO.DirectoryInfo', 'System.IO.FileInfo' |
| 16 | + #> |
| 17 | + param( |
| 18 | + # The name of the selection set. |
| 19 | + [Parameter(Mandatory,ValueFromPipelineByPropertyName)] |
| 20 | + [Alias('SelectionSetName','SelectionSet')] |
| 21 | + [string] |
| 22 | + $Name, |
| 23 | + |
| 24 | + # The type names in the selection set. |
| 25 | + [Parameter(Mandatory,ValueFromPipelineByPropertyName)] |
| 26 | + [string[]] |
| 27 | + $TypeName |
| 28 | + ) |
| 29 | + |
| 30 | + begin { |
| 31 | + # First, create a queue to hold the selection sets. |
| 32 | + $eachSelectionSet = [Collections.Queue]::new() |
| 33 | + } |
| 34 | + |
| 35 | + process { |
| 36 | + # Make sure the name and type names are XML-safe |
| 37 | + $NameAsXml = "<Name>$Name</Name>" -as [xml] |
| 38 | + if (-not $NameAsXml) { |
| 39 | + $Name = [Security.SecurityElement]::Escape($Name) |
| 40 | + } |
| 41 | + $TypeName = foreach ($tn in $TypeName) { |
| 42 | + if (-not ("<TypeName>$tn</TypeName>" -as [xml])) { |
| 43 | + [Security.SecurityElement]::Escape($tn) |
| 44 | + } else { |
| 45 | + $tn |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + # Create the selection set XML |
| 50 | + $selectionSetXml = [xml](@( |
| 51 | + "<SelectionSet>" |
| 52 | + # Consisting of a `<Name>` |
| 53 | + "<Name>$Name</Name>" |
| 54 | + "<Types>" # and a `<Types>` element |
| 55 | + foreach ($tn in $TypeName) { |
| 56 | + # (containing each `<TypeName>`) |
| 57 | + "<TypeName>$tn</TypeName>" |
| 58 | + } |
| 59 | + "</Types>" |
| 60 | + "</SelectionSet>" |
| 61 | + ) -join '') |
| 62 | + if (-not $selectionSetXml) { return } |
| 63 | + $xOut=[IO.StringWriter]::new() |
| 64 | + $selectionSetXml.Save($xOut) |
| 65 | + $eachSelectionSet.Enqueue("$xOut" -replace '\<\?xml.+?\?>[\s\r\n]+') |
| 66 | + $xOut.Dispose() |
| 67 | + } |
| 68 | + |
| 69 | + end { |
| 70 | + # Create the `<SelectionSets>` element |
| 71 | + $selectionSetXml = @( |
| 72 | + "<SelectionSets>" |
| 73 | + # (containing each `<SelectionSet>`) |
| 74 | + $eachSelectionSet.ToArray() |
| 75 | + "</SelectionSets>" |
| 76 | + ) -join '' -as [xml] |
| 77 | + $xOut=[IO.StringWriter]::new() |
| 78 | + $selectionSetXml.Save($xOut) |
| 79 | + # Write the XML to the pipeline as a string, removing the XML declaration. |
| 80 | + "$xOut" -replace '\<\?xml.+?\?>[\s\r\n]+' |
| 81 | + $xOut.Dispose() |
| 82 | + } |
| 83 | +} |
0 commit comments