PoshCode Archive  Artifact [58c3a27968]

Artifact 58c3a27968a27bcefa7836f2e86c85b071cad1af3f63eefeb7c15cceaf83e2a8:

  • File Select-CLSCompliant.ps1 — part of check-in [23aeee80ad] at 2018-06-10 13:14:47 on branch trunk — The beginnings of a function for handling ETS exceptions thrown by types which are not CLS Compliant when you try to output them. (user: Joel Bennett size: 1509)

# encoding: ascii
# api: powershell
# title: Select-CLSCompliant
# description: The beginnings of a function for handling ETS exceptions thrown by types which are not CLS Compliant when you try to output them.
# version: 0.1
# type: function
# author: Joel Bennett
# license: CC0
# function: Select-CLSCompliant
# x-poshcode-id: 2721
# x-archived: 2011-12-15T09:10:50
# x-published: 2011-06-09T13:27:00
#
# Now inserts the correct Type name into the output object.
#
function Select-CLSCompliant {
#.Synopsis
#  Outputs the same as "Select-Object *" with basic error handling for properties that are not CLS Compliant

[CmdletBinding()]
param([Parameter(ValueFromPipeline=$true)]$InputObject)
process {
   foreach($in in $InputObject) {
      $In | Select-Object *

      trap [System.Management.Automation.ExtendedTypeSystemException] {
         $m = $_.Exception.Message
         $matches = [regex]::Matches($m, 'The field/property: \"(?<field>.*)\" for type: \"(?<Type>[^"]+)\" .* Failed to use non CLS compliant type.')
         $type = $matches[0].Groups["Type"].Value -as [Type]
         
            
         $properties = $type.GetProperties()
         $output = @{}
         $properties | %{ $Output.($_.Name) = $_.GetValue( $In, $null ) }
         $NewObject = new-Object PSObject -Property $Output
         $NewObject.pstypenames.insert(0,"Selected." + ($matches[0].Groups["Type"].Value))
         Write-Output $NewObject
         continue
      }
   }
}}