Luc*_*ino 5 powershell formatting
我的模块中有一个cmdlet,它从数据库表中返回一个通用DataRows的集合,其名称用-Name参数指定
# this returns a collection of datarows from table "Orders"
Get-Table -Name Orders
Run Code Online (Sandbox Code Playgroud)
每次我在不同的表上调用cmdlet时,我都会将输出管道化Format-Table,使其更具可读性.
有没有办法保持属性格式化为表,而不必每次都管道Format-Table?是什么告诉PowerShell总是使用表格布局来显示DataRow类型?
我已经有了一个ps1xml文件和模块,包含一些格式规则,如下所示:
<View>
<Name>MyType</Name>
<ViewSelectedBy>
<TypeName>MyNamespace.MyType</TypeName>
</ViewSelectedBy>
<TableControl>
<TableRowEntries>
<TableRowEntry>
<TableColumnItems>
<TableColumnItem>
<PropertyName>Property1</PropertyName>
</TableColumnItem>
<TableColumnItem>
<PropertyName>Property2</PropertyName>
</TableColumnItem>
[...]
</TableColumnItems>
</TableRowEntry>
</TableRowEntries>
</TableControl>
</View>
Run Code Online (Sandbox Code Playgroud)
我想对System.Data.DataRow类型使用类似的规则,但属性每次都有不同的名称,似乎我无法<TableRowEntries>从上面的XML模板中删除标记.
任何的想法?
我想说,仅仅为了让 PowerShell 将对象输出为表格而编写自定义格式文件太费力了。
如果您真的想尝试,那么您已经走在正确的道路上。
我想出了一个简单的格式定义,将 DataRows 输出为表格。
但有一个警告:我认为不可能为每一列都有自定义标签(您必须再次检查架构定义:https ://msdn.microsoft.com/en-us/library/gg580910(v =vs.85).aspx )。在我的示例中,我仅使用“Field1”、“Field2”等通用名称。
以下是 2 列的格式定义:
$TableFormat = @'
<Configuration>
<ViewDefinitions>
<View>
<Name>MyTable</Name>
<ViewSelectedBy>
<TypeName>System.Data.DataRow</TypeName>
</ViewSelectedBy>
<TableControl>
<TableHeaders>
<TableColumnHeader>
<Label>Field 1</Label>
<Width>20</Width>
</TableColumnHeader>
<TableColumnHeader>
<Label>Field 2</Label>
<Width>20</Width>
</TableColumnHeader>
</TableHeaders>
<TableRowEntries>
<TableRowEntry>
<TableColumnItems>
<TableColumnItem>
<ScriptBlock>$_.Item(0)</ScriptBlock>
</TableColumnItem>
<TableColumnItem>
<ScriptBlock>$_.Item(1)</ScriptBlock>
</TableColumnItem>
</TableColumnItems>
</TableRowEntry>
</TableRowEntries>
</TableControl>
</View>
</ViewDefinitions>
</Configuration>
'@
Run Code Online (Sandbox Code Playgroud)
更新格式定义:
$FormatPath = Join-Path -Path $PSScriptRoot -ChildPath "DataTable.format.ps1xml"
$TableFormat | Set-Content -Path $FormatPath -Encoding Default
Update-FormatData -Appendpath $FormatPath
Run Code Online (Sandbox Code Playgroud)
以及一个示例输出:
$CnStr = "Data Source=Starbase1\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=SSPI"
$Sql = "Select LastName, City From Employees Where City <> 'Seattle'"
$Da = New-Object -TypeName System.Data.SqlClient.SqlDataAdapter -ArgumentList $Sql, $CnStr
$Ta = New-Object -TypeName System.Data.DataTable
$Da.Fill($Ta)
$Ta
Run Code Online (Sandbox Code Playgroud)