选择并遍历属性

时间:2019-04-23 07:08:07

标签: powershell

我正在尝试从属性列表中读取内容,其中一个属性是一个对象。我需要使用什么来读取字符串和对象属性?

以下是列表Get-Member的输出

PS> $r | Get-Member

Name              MemberType Definition
----              ---------- ----------
Equals            Method     bool Equals(System.Object obj)
GetHashCode       Method     int GetHashCode()
GetType           Method     type GetType()
ToString          Method     string ToString()
ActivityName      Property   string ActivityName {get;}
DurationInMs      Property   System.Nullable[int] DurationInMs {get;}
Error             Property   System.Object Error {get;}
Input             Property   System.Object Input {get;}
Output            Property   System.Object Output {get;}
Status            Property   string Status {get;}


PS> $r.Output | Get-Member

...
Name            Property       string Name {get;}
Next            Property       Newtonsoft.Json.Linq.JToken Next {get;}
Path            Property       string Path {get;}
Previous        Property       Newtonsoft.Json.Linq.JToken Previous {get;}
Root            Property       Newtonsoft.Json.Linq.JToken Root {get;}
...

(这是一长串,隐藏了不必要的细节)

我试图以表格格式选择ActivityName,DurationInMs和Outputs的值。输出对象中的“根属性”具有dataRead,dataWritten属性的值。

这是我尝试过的:

$r | Select ActivityName,DurationInMs

输出:

ActivityName     DurationInMs
------------     ------------
SetDay                     78
Set TS                     15
LKUP_FileControl        12206
CopyPaths               38585

我也尝试过:

$r.Output | select @{name="dataRead"; expression={$_.Root.dataRead.Value}},@{name="dataWritten"; expression={$_.Root.dataWritten.Value}}

输出:

dataRead     dataWritten
--------     -----------


520114512    520114512
520114512    520114512
520114512    520114512
0            0
0            0
0            0
3199091788   3199091788
3199091788   3199091788
3199091788   3199091788

(注意:这会导致重复,因为Root属性内部还有其他嵌套属性)

我希望输出为表格格式,例如:

ActivityName     DurationInMs    dataRead      dataWritten
------------     ------------    ---------    ------------
SetDay                     78
Set TS                     15    520114512       520114512
LKUP_FileControl        12206            0               0
CopyPaths               38585   3199091788      3199091788

如何在PowerShell中执行此操作?

1 个答案:

答案 0 :(得分:0)

组合两个代码段以获得所需的结果:

$r | Select-Object ActivityName, DurationInMs,
    @{n='dataRead';e={$_.Output.Root.dataRead.Value}},
    @{n='dataWritten';e={$_.Output.Root.dataWritten.Value}}