powershell - 将类名解析为类型加速器名称
问题描述
我偶然发现了如何使用 一致地获取类的类型加速器名称(即短名称)"$(...)"
,例如:
PS H:\> "$([System.DirectoryServices.DirectorySearcher])"
adsisearcher
PS H:\> "$([adsisearcher])"
adsisearcher
PS H:\> "$([type]'System.DirectoryServices.DirectorySearcher')"
adsisearcher
PS H:\> "$([type]'adsisearcher')"
adsisearcher
或者,如果您有该类的实例:
PS H:\> "$(([System.DirectoryServices.DirectorySearcher]'').GetType())"
adsisearcher
PS H:\> "$(([adsisearcher]'').GetType())"
adsisearcher
但是查看该类的属性(例如[System.DirectoryServices.DirectorySearcher] | fl
),我实际上在其中的任何地方都看不到“adsisearcher”。调用ToString()
也无济于事,因为您获得了完整的类名:
PS H:\> [System.DirectoryServices.DirectorySearcher].ToString()
System.DirectoryServices.DirectorySearcher
PS H:\> [adsisearcher].ToString()
System.DirectoryServices.DirectorySearcher
谁能解释这"$(...)"
实际上是如何解析短名称的?“回报价值”从何而来?
SO上有许多其他答案解释了如何获取类型加速器的完整列表,但我找不到任何解释这种"$(...)"
行为的答案。
解决方案
这不是执行它的$()
操作,而是从[type]
to的转换[string]
:
PS H:\> [System.Int32] -as [string]
int
对于代码生成用例,类型名称转换也通过LanguagePrimitives.ConvertTypeNameToPSTypeName()
静态方法公开,该方法在给定可解析类型名称的情况下生成有效的类型文字标记:
PS H:\> [System.Management.Automation.LanguagePrimitives]::ConvertTypeNameToPSTypeName('System.Int32')
[int]
PS H:\> [System.Management.Automation.LanguagePrimitives]::ConvertTypeNameToPSTypeName('System.DirectoryServices.DirectorySearcher')
[adsisearcher]
但是查看该类的属性(例如
[System.DirectoryServices.DirectorySearcher] | fl
),我实际上在其中的任何地方都看不到“adsisearcher”。
这是因为类型加速器是 PowerShell在底层 (.NET) 类型系统之上强加的类型名称别名——目标类型本身对“类型加速器”是什么一无所知。
内置类型加速器名称的真正“起源”是PowerShell 语言引擎中类型映射的硬编码列表
推荐阅读
- node.js - 如何从我的 Angular Nodejs Web 应用程序请求 Gemini Order Events WebSocket?
- python - Selenium:代码运行时禁用无头?(Python)
- docsify - 我无法为 docsify 安装复制代码插件
- git - 如何在不更改主存储库的情况下在本地将我的存储库恢复到其原始状态?
- c - 错误:“?”之前的预期表达式 令牌
- javascript - 在 React 中从子组件更改父状态(无 Redux)
- git - 如何使“git difftool --dir-diff”与 vim 一起工作
- javascript - 将组件添加到内容可编辑的 div 后如何添加光标位置
- c# - ASP.NET MVC 外部登录重定向 URi 从 http 到 https
- c# - 无法从 JSON 格式检索正确的值。需要协助