查看Powershell自定义类型格式定义



当我有一个使用自定义类型格式的对象时,查找和查看其定义的最简单方法是什么?

例如,类型[Microsoft.Win32.RegistryKey]具有在默认powershell安装目录中定义的自定义格式。它很长,但我真正感兴趣的只是为特定类型运行任何ScriptBlock项——这个定义中的示例字段:

<!-- C:WindowsSystem32WindowsPowerShellv1.0Registry.format.ps1xml -->
<ScriptBlock>$_.PSParentPath.Replace("Microsoft.PowerShell.CoreRegistry::", "")</ScriptBlock>
<TypeName>Microsoft.Win32.RegistryKey</TypeName>
<ScriptBlock>
$result = (Get-ItemProperty -LiteralPath $_.PSPath |
Select * -Exclude PSPath,PSParentPath,PSChildName,PSDrive,PsProvider |
Format-List | Out-String | Sort).Trim()
$result = $result.Substring(0, [Math]::Min($result.Length, 5000) )
if($result.Length -eq 5000) { $result += "..." }
$result
</ScriptBlock>

有没有一种方法可以查看特定类型是否有自定义格式,以及它在哪里定义?我四处探索了类型的属性等等——希望我能看到一些对模块的引用或加载类型的东西:

[Microsoft.Win32.RegistryKey].Module
FullyQualifiedName : C:WindowsMicrosoft.NETFramework64v4.0.30319mscorlib.dll
Name               : mscorlib.dll

我碰巧知道这是从PSSnapin而不是模块加载的,我可以看到它有一个Formats属性,列出了格式xml文件:

Get-PSSnapin Microsoft.PowerShell.Core | fl Name,ModuleName,Formats

Name       : Microsoft.PowerShell.Core
ModuleName : C:WindowsSystem32WindowsPowerShellv1.0System.Management.Automation.dll
Formats    : {Certificate.format.ps1xml, DotNetTypes.format.ps1xml, 
FileSystem.format.ps1xml, Help.format.ps1xml...}

但我不确定在事先不知道的情况下如何发现这一点,我仍然需要打开文件,看看它们是否包含类型名称。

我最终通过about_Format.ps1xml找到了Get-FormatData,它在给定类型时返回一个具有格式设置(如果有的话(的对象

$FormatData = Get-FormatData -PowerShellVersion ($PSVersionTable.PSVersion) -TypeName 'Microsoft.Win32.RegistryKey'
$FormatData.FormatViewDefinition.Control.Rows.Columns.DisplayEntry.Value
#Returns:
$result = (Get-ItemProperty -LiteralPath $_.PSPath |
Select * -Exclude PSPath,PSParentPath,PSChildName,PSDrive,PsProvider |
Format-List | Out-String | Sort).Trim()
$result = $result.Substring(0, [Math]::Min($result.Length, 5000) )
if($result.Length -eq 5000) { $result += "..." }
$result

它似乎不包含ps1xml文件的路径,但我可以Export-FormatData在某个地方创建一个副本。

最新更新