英文:
How to get full type name from the short name and vice-versa?
问题
如果我有一个对象类型的简短名称(例如:PSCredential,String等),我需要获取完整的类型名称(例如:System.Management.Automation.PSCredential,System.String等),反之亦然。
我认为这应该很容易通过使用 Get-TypeData
来实现,但由于某种奇怪的原因,该命令返回了PSCredential和ServiceController等类型的信息,但对于基本类型如String、Int32、Boolean等,却没有返回任何信息。
有人知道如何实现这一目标吗?
英文:
If I have the short name of an object type (eg: PSCredential, String, etc) I need to get the full type name (eg: System.Management.Automation.PSCredential, System.String, etc), and vice-versa.
I would think this would be as easy as using Get-TypeData
, but for some weird reason that command returns info for types like PSCredential and ServiceController, but nothing for basic types like String, Int32, Boolean, etc.
Does anyone know how to accomplish this?
答案1
得分: 3
你可以通过调用类型的 .FullName
属性 来获取类型的完全限定名称,例如:
[pscredential].FullName # => System.Management.Automation.PSCredential
从完全限定名称到 .Name
,你可以将字符串转换为 [type]
:
([type] 'System.Management.Automation.PSCredential').Name # => PSCredential
如果你想查看它们的 加速器名称,例如:bool
而不是 Boolean
(假设它们有一个),你可以使用以下方法:
$accelerators = @{}
[PowerShell].Assembly.GetType('System.Management.Automation.TypeAccelerators')::Get.GetEnumerator() |
ForEach-Object { $accelerators[$_.Value.FullName] = $_.Key }
然后你可以执行:
$accelerators['System.Boolean'] # => bool
如评论中的 OP 所指出,在某些情况下上述方法可能会失败,当尝试 [type] 'Process'
时,可以尝试以下方法:
$map = @{}
[System.AppDomain]::CurrentDomain.GetAssemblies() |
ForEach-Object { try { $_.GetExportedTypes() } catch { } } |
ForEach-Object {
$map[$_.Name] = $_.FullName
$map[$_.FullName] = $_.Name
}
$map['Process'] # => System.Diagnostics.Process
$map['System.Diagnostics.Process'] # => 'Process'
希望这些信息对你有所帮助。
英文:
You can get the fully qualified name of a type by calling the type's .FullName
property, i.e.:
[pscredential].FullName # => System.Management.Automation.PSCredential
From the fully qualified name to the .Name
you can cast the string as [type]
:
([type] 'System.Management.Automation.PSCredential').Name # => PSCredential
If you want to see their accelerator name i.e.: bool
instead of Boolean
(assuming they have one) you can use the following:
$accelerators = @{}
[PowerShell].Assembly.GetType('System.Management.Automation.TypeAccelerators')::Get.GetEnumerator() |
ForEach-Object { $accelerators[$_.Value.FullName] = $_.Key }
Then you can do:
$accelerators['System.Boolean'] # => bool
The above might certainly fail in some cases, as noted by OP in comments, while trying [type] 'Process'
, the following should work in such cases:
$map = @{}
[System.AppDomain]::CurrentDomain.GetAssemblies() |
ForEach-Object { try { $_.GetExportedTypes() } catch { } } |
ForEach-Object {
$map[$_.Name] = $_.FullName
$map[$_.FullName] = $_.Name
}
$map['Process'] # => System.Diagnostics.Process
$map['System.Diagnostics.Process'] # => 'Process'
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论