首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >自动检索受限语言模式的允许类型

自动检索受限语言模式的允许类型
EN

Stack Overflow用户
提问于 2020-11-12 14:14:09
回答 1查看 525关注 0票数 7

对于我的业余项目ConvertTo-Expression,我希望我的cmdlet的输出表达式(默认情况下)符合约束语言模式。为此,我可能包括一个硬编码的列表,其中包含允许的类型。

代码语言:javascript
复制
$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],
    ...

但是,我更自动地从本身检索允许类型的列表,因为它知道这将是最最新的版本(例如,[Ordered]类型没有在网站上列出,但似乎在受限的语言模式下是允许的)。

有办法这样做吗?

或者:

如何检查(在 language模式中)特定类型是否符合约束的语言模式

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-11-12 15:32:43

如何检查(在完全语言模式下)某个特定类型是否符合受约束的语言模式?

您可以根据下面进一步定义的Test-TypePermitted函数使用以下内容:

代码语言:javascript
复制
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 

官方docs re PowerShell语言模式(您也可以从问题中链接到该模式):模式

Test-TypePermitted 函数:

代码语言:javascript
复制
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()
  }

}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64805592

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档