函数,用于生成用于Format-Table的计算属性



下面是两个对象的简单列表:

$ls = 
[PSCustomObject]@{ a = 10; b = 20; c = 30; },
[PSCustomObject]@{ a = 40; b = 50; c = 60; }

使用计算属性的ft显示列表:

$ls | ft `
@{ Label = ':a:'; Expression = { $_.a } }, 
@{ Label = ':b:'; Expression = { $_.b } }, 
@{ Label = ':c:'; Expression = { $_.c } }

我们得到:

:a: :b: :c:
--- --- ---
10  20  30
40  50  60

这些计算出来的属性要输入很多。因此,如果有一个函数为我们创建一个,那就太好了。

就像这样:

function create-format ($name)
{
@{ Label = (':{0}:' -f $name); Expression = { $_.$name } }
}

所以我们可以这样做:

$ls | ft `
(create-format 'a'), 
(create-format 'b'), 
(create-format 'c')

当然不行。

它不工作,因为scriptblock:

{ $_.$name }

不以计算$name结束。

我们可以看到这一点。如果我们调用:

create-format 'a'

我们得到:

Name                           Value
----                           -----
Expression                      $_.$name
Label                          :a:
<标题>

设置create-format的好方法是什么

这似乎奏效了:

function create-format ($name)
{
@{ 
Label = (':{0}:' -f $name)
Expression = [System.Management.Automation.ScriptBlock]::Create('$_.' + $name)
}
}

真实的例子下面是一个使用上述技巧的例子:

function create-format ($name)
{
@{ 
Label = $name
Expression = [System.Management.Automation.ScriptBlock]::Create('$_.{0}.ToString("N0")' -f $name)
Align = 'right'
}
}

最新更新