Automatically retrieve Allowed Types for Constrained Language mode
Asked Answered
E

1

7

For my hobby project ConvertTo-Expression, I would like the output expression of my cmdlet (by default) compliant with the Constrained Language mode. For this, I might include a hardcoded list with Allowed Types:

$AllowedTypes = # https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_language_modes?view=powershell-7
    [Array],
    [Bool],
    [byte],
    [char],
    [DateTime],
    [decimal],
    ...

but I rather automatically retrieve the list of Allowed Types from PowerShell itself, knowing that would be most up-to-date version (e.g. the [Ordered] type isn't listed on the website but does appear to be allowed in Constrained Language mode).

Is there a way to do this?
Or:
How can I check (in full language mode) if a specific type is compliant with constrained language mode?

Ephemerid answered 12/11, 2020 at 14:14 Comment(3)
Good question. Quick aside re [ordered], so others know: it isn't a type (literal) as such and can only be used as part of the syntactic sugar construct [ordered] @{ ... }, which allows you to create an ordered hash table (dictionary), i.e. one whose entries are maintained in definition order. The underlying .NET type is [System.Collections.Specialized.OrderedDictionary].Popular
... which isn't in the list on the internet either.Ephemerid
@mklement0, I created a docs issue but I think that there is actually a bug (or big inconsistency) here, see: Incomplete Allowed Types list.Ephemerid
P
4

How can I check (in full language mode) if a specific type is compliant with constrained language mode?

You can use something like the following, based on the Test-TypePermitted function defined further below:

PS> [System.IO.FileInfo], [int] | Test-TypePermitted -Mode Constrained

TypeName           Permitted Message
--------           --------- -------
System.IO.FileInfo     False Cannot create type. Only core types are supported in this language mode.
System.Int32            True 

Official docs re PowerShell language modes (which you also link to from the question): about_Language_Modes


Test-TypePermitted function:

function Test-TypePermitted {

  [CmdletBinding(PositionalBinding = $false)]
  param(
    [Parameter(ValueFromPipeline, Position = 0)]
    [Type[]] $Type
    ,
    [Parameter(Position = 1)]
    [Alias('Mode')]
    [ValidateSet('Restricted', 'Constrained', 'FullLanguage')]
    $LanguageMode = 'Constrained'
  )

  begin {
    try {
      $ps = [powershell]::Create()
      $ps.Runspace.SessionStateProxy.LanguageMode = $LanguageMode
    } catch { Throw }
  }

  process {
    foreach ($t in $type) {

      $expression = switch -Wildcard ($LanguageMode) {
        'Restricted*' {
          # In 'RestrictedLanguage' mode, seemingly just referencing the *type*
          # of a non-permitted type causes an error.
          '[{0}]' -f $t.FullName
        }
        Default {
          # In 'ConstrainedLanguage' mode, whether a type is permitted or not
          # only surfaces when you try to *construct an instance*.
          # Note: New-Object can construct value types even without argument.
          #       For reference types, it succeeds only if there is a (public)
          #       parameterless constructor.
          #       However, fortunately, construction isn't even attempted if
          #       the type isn't permitted.
          'New-Object ''{0}''' -f $t.FullName
        }
      }

      $message = $null
      $permitted = try {
        if ($ps.AddScript($expression).Invoke().Count -ne 0) {
          $true
        } elseif ($ps.Streams.Error[0].FullyQualifiedErrorId -Match 'CannotFindAppropriateCtor') {
          # Type is permitted in principle, but couldn't be constructed due to not having a parameterless constructor.
          $true
        } else {
          # Type is not permitted.
          $message = $ps.Streams.Error[0].ToString()
          $false
        }
      } catch { # Happens in RestrictedLanguage mode.
        # Type is not permitted.
        $message = ($_.ToString() -split '\r?\n')[-1].TrimEnd('"')
        $false
      }
    }

    [pscustomobject] @{
      TypeName = $t.FullName
      Permitted = $permitted
      Message = $message
    }

    # Prepare for next iteration.
    $ps.Commands.Clear(); $ps.Streams.ClearStreams()
  }

  end {
    $ps.Dispose()
  }

}
Popular answered 12/11, 2020 at 15:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.