Alex Snigirev
Alex Snigirev

Reputation: 67

How use "Where-Object" condition with '[PScustomobject]'?

I have some code:

$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[,]   

I need to sort and filter my $output, but I can't. Nothing happens. Probably doing something wrong.

PS> $output

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

And my condition:

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...}   

Upvotes: 0

Views: 2379

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200553

You created a single object with 2 properties, each of which contains all values of its associated column. Since Sort-Object and Where-Object sort and filter lists of objects by their properties there's nothing for these cmdlets to do here.

What you actually want to do is create one object per row.

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

Untested, since I don't have MS Office at hand here.

Upvotes: 2

Related Questions