0

I am using Powershell and am having trouble with the Where-Object cmdlet. I currently select * and then want to only output when a field is equal to Alabama. This field could be under any column, not just one.

This is what I have:

select * | where {$_.state_name -eq 'Alabama'} . 

This works for state_name, but i cant get all columns without doing them individually. I've tried where{$_ -eq....} but that doesn't work.

3
  • From what are you selecting? Did you try $_.state_name instead? Note the period . after $_ Commented Apr 14, 2015 at 16:32
  • That was a typo. I meant $_. Im trying to select all where propertyname= 'Alabama' Commented Apr 14, 2015 at 16:35
  • This sounds like stackoverflow.com/questions/29529154/… as well Commented Apr 14, 2015 at 17:28

2 Answers 2

3

Kind of a hack, but:

select * | where {($_ | ConvertTo-Csv -NoTypeInformation)[1] -like '*"Alabama"*'}
Sign up to request clarification or add additional context in comments.

3 Comments

Nah, not much of a hack IMO. The only option is to somehow concatenate all the fields together then check the concatenated value for the string. CSV is a decent way to do that.
I can think of one edge case that would cause a problem. If there is a property name that matched the search string that would be a problem.
@EBGreen. I thought of that, and added the [1] to slice off just the data row.
3

You have to iterate over all object's properties and check if it contains word 'Alabama'.

Example:

# Import CSV file and feed it to the pipeline
Import-Csv -Path .\My.csv |
    # For each object
    ForEach-Object {
        # Psobject.Properties returns all object properties
        # (Psobject.Properties).Value returns only properties' values
        # -contains operator checks if array of values contains exact string 'Alabama'
        # You can also use -like operator with wildcards, i.e. -like '*labama'
        if(($_.PSObject.Properties).Value -contains 'Alabama')
        {
            # If any of the object properties contain word 'Alabama',
            # write it to the pipeline, else do nothing.
            $_
        }
    }

3 Comments

This could just be reduced to Import-Csv C:\Temp\data.csv | Where-Object{($_.PSObject.Properties).Value -contains 'Alabama'}
I think this is a true answer to the question, as it natively pulls the needed properties/values from the object in flight, rather than effectively re-importing the values, as the other answer does.
@Matt +1, I've missed that.

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.