如何在“[PScustomobject]”中使用“Where-Object”条件?

时间:2018-01-11 12:32:22

标签: powershell powershell-v4.0

我有一些代码:

$output = [PSCustomObject]@{
    Name       = $ws.UsedRange.Columns.Item(1).Value2
    Department = $ws.UsedRange.Columns.Item(3).Value2
}

$output | GM
TypeName: System.Management.Automation.PSCustomObject

Name        MemberType   Definition                                  
----        ----------   ----------                                  
Equals      Method       bool Equals(System.Object obj)              
GetHashCode Method       int GetHashCode()                           
GetType     Method       type GetType()                              
ToString    Method       string ToString()                           
Department  NoteProperty System.Object[,] Department=System.Object[,]
Name        NoteProperty System.Object[,] Name=System.Object[,]   

我需要对$output进行排序和过滤,但我不能。什么都没发生。可能做错了。

PS> $output

Name                             Department                                     
----                             ----------                                    
{Numbers, 1,2,3,4,5,6,7...}      {Sales,IT,Accounting,Developers...}       

我的情况:

PS> $output | Sort-Object Department -Descending | Where-Object {$_.Department -eq "Sales"}

Name                             Department                                     
----                             ----------                                    
{Numbers, 1,2,3,4,5,6,7...}      {Sales,IT,Accounting,Developers...}   

1 个答案:

答案 0 :(得分:2)

您创建了一个包含2个属性的对象,每个属性都包含其关联列的所有值。由于Sort-ObjectWhere-Object按其属性对对象列表进行排序和过滤,因此这些cmdlet无需执行此操作。

您实际想要做的是每行创建一个对象

$output = foreach ($row in $ws.UsedRange.Rows) {
    [PSCustomObject]@{
        Name       = $row.Columns.Item(1).Value2
        Department = $row.Columns.Item(3).Value2
    }
}

未经测试,因为我手边没有MS Office。