PowerShell自定义格式

时间:2015-07-10 19:35:17

标签: powershell powershell-v3.0

我想显示/自定义SharePoint列表中的属性子集(通过OData API),这些属性已从JSON转换为PsCustomObject。

为此,我创建了一个自定义格式文件(PsFoobar.Format.ps1xml),我希望将其用于PowerShell模块:

<?xml version="1.0" encoding="utf-8"?>
<Configuration>
  <ViewDefinitions>
    <View>
      <Name>RequestView</Name>
      <ViewSelectedBy>
        <TypeName>System.Management.Automation.PsCustomObject</TypeName>
      </ViewSelectedBy>
      <TableControl>
        <TableHeaders>
          <TableColumnHeader>
            <Width>4</Width>
          </TableColumnHeader>
          <TableColumnHeader>
            <Width>25</Width>
          </TableColumnHeader>
        </TableHeaders>
        <TableRowEntries>
          <TableRowEntry>
            <TableColumnItems>
              <TableColumnItem>
                <PropertyName>Id</PropertyName>
              </TableColumnItem>
              <TableColumnItem>
                <PropertyName>Title</PropertyName>
              </TableColumnItem>
            </TableColumnItems>
          </TableRowEntry>
        </TableRowEntries>
      </TableControl>
    </View>
  </ViewDefinitions>
</Configuration>

我在模块的清单(.psd1)中引用了它:

TypesToProcess = @('PsFoobar.Format.ps1xml')

当我尝试加载模块时,出现错误:

import-module : The following error occurred while loading the extended type data file:
, C:\Users\...\WindowsPowerShell\Modules\PsFoobar\PsFoobar.Format.ps1xml(0) : Error:
The node Configuration cannot be present. Nodes allowed are: Types.
, C:\Users\...\WindowsPowerShell\Modules\PsFoobar\PsFoobar.Format.ps1xml(0) : Error:
Node "Types" was not found. It should be present once under "Document". The parent node "Document" will be ignored.
At line:1 char:1
+ import-module PsFoobar -force
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [Import-Module], RuntimeException
    + FullyQualifiedErrorId : FormatXmlUpdateException,Microsoft.PowerShell.Commands.ImportModuleCommand

我错过了什么?

1 个答案:

答案 0 :(得分:1)

您在模块清单中使用了错误的密钥。对于格式数据,您应使用FormatsToProcess代替TypesToProcess

顺便说一句,System.Management.Automation.PSCustomObject是所有自定义对象的通用类型名称。例如:Select-Object cmdlet返回的对象具有该类型名称。通过添加格式定义,您可能会破坏所有对象的显示。我建议您将自定义标记添加到类型名称:

<TypeName>System.Management.Automation.PSCustomObject#MySharePointData</TypeName>

并将此类型名称添加到对象中:

ConvertFrom-Json ...|Add-Member -TypeName System.Management.Automation.PSCustomObject#MySharePointData -PassThru