3

I am not sure how to do this with the usual suspects, namely Where-Object or Select-Object.

Suppose I want to find the string "needle" in PSCustomObject $Object, and that object can have several Note properties, such as $Object.Haystack1, $Object.Haystack2 and so on ..

In my case the number of note properties is known and fixed, but I'd like to know what to do for the harder case when you don't know how many properties your object has.

I poked around with Select/Where-Object and the operator -in but hadn't managed to make an easy, elegant one liner that does the job.

Matt
  • 45,022
  • 8
  • 78
  • 119
Bluz
  • 5,980
  • 11
  • 32
  • 40
  • 1
    Don't design your program so you need to do that? – TessellatingHeckler Jun 28 '16 at 21:12
  • I thought somebody would have made that comment ;) Unfortunately, it's nothing I designed. It's for that odd case when you have 2 different pieces of software providing similar information on data export but you need to filter/match their output. – Bluz Jun 29 '16 at 19:56
  • @Matt thanks very much for your contribution to syntax coloration, however the semantics style wasn't your place to change. "always respect the original author" includes the tone in which they want to convey the message as long as it's not blatantly offensive - merci buckets :) – Bluz Jul 01 '16 at 12:15
  • I didn't the message of the question at all. I made some word and case changes and removed the tag in the title as well as some text that added nothing to the question. This makes it more likely for other users to find your content which is what SO is about and what my edits and future edits are for. Nothing I did changed the syntax colouring either. No part of my changes deviates from your intent. I did use code markup which helps users understand regular speech from code. It might be obvious to you but not everyone. – Matt Jul 01 '16 at 14:37

3 Answers3

7
$obj = [pscustomobject]@{'Haystack1'='test';'Haystack2'='needle'}

$noteProperties = $obj|get-member -MemberType NoteProperty | select -ExpandProperty name
$noteProperties | Where {$obj."$_" -match 'needle'}

and you can one-liner it with

$obj|gm -M NoteProperty|?{$obj."$($_.Name)"-match'needle'}
TessellatingHeckler
  • 27,511
  • 4
  • 48
  • 87
4

One possibility:

$obj = [pscustomobject]@{'Haystack1'='test';'Haystack2'='needle'}
@($obj | Format-List *| Out-String).split("`n") -like '*needle*'

Haystack2 : needle
mjolinor
  • 66,130
  • 7
  • 114
  • 135
0
$obj = [PSCustomObject]@{"Haystack1" = "test"; "Haystack2" = "needle"}
$obj.PSObject.Properties | ? { $_.Value -eq "needle" }