0

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...}   
3
  • You've created a single PSCustomObject, with two fields Name and Department. Is this what you wanted to do? Commented Jan 11, 2018 at 12:36
  • I have excel file with 2 main 'Columns' (Number, Department) . ~ 660 rows. I will want extract these rows in [pscustomobject] and after use 'sort' and 'where' condition in order to be able to filter data by department. Commented Jan 11, 2018 at 12:40
  • 1
    You might want to consider whether it's not more appropriate to save the Excel file as a CSV, and then process it via Import-CSV piped to ForEach-Object. Commented Jan 11, 2018 at 12:43

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.