-1

I am trying to select the variable name from a selection of variables that is missing a value:

Only $fruit is missing "Pears" and I want to only list that.

$fruit = @('Apples','Oranges','Bananas')
$fruit2 = @('Apples','Oranges','Bananas', 'Pears')
$fruit3 = @('Apples','Oranges','Bananas', 'Pears')

So I need the code to find the variable name $fruit but I when I try this:

$fruit, $fruit2, $fruit3 | ?{$_ -notcontains "Pears"} | Select $_

It only lists the 3 fruits in the variable that does not contain "Pears"

How do I get it to list $fruit as the result?

IanB
  • 271
  • 3
  • 13
  • 1
    A hashtable keyed on Fruit, Fruit1, Fruit2 with the associated value being the array would probably be the way to go.... – Keith Miller Dec 31 '22 at 04:38
  • What exactly do you expect as a result? The literal word `$fruit`???What should be the outcome if `$fruit3` is also missing `pears` or has e.g. `lemons` instead of `pears`. Please think your question through before [asking](https://stackoverflow.com/help/how-to-ask) – iRon Dec 31 '22 at 08:46
  • Apologies, I want the variable that does not contain the pears to be produced as the result. The actual use case is to interrogate a bunch of computers for the absence of a particular application, I tried to simplify the example to learn how to filter objects that contain a lot of things but only show the objects that have something specific missing. – IanB Dec 31 '22 at 10:30
  • $fruit = @('Apples','Oranges','Bananas'); $fruit2 = @('Apples','Oranges','Bananas', 'Pears'); $fruit2 | Where {-not $fruit.Contains($_)} – jdweng Dec 31 '22 at 11:46
  • You would probably want to read this: [Powershell | how to programmatically iterate through variable names](https://stackoverflow.com/a/65250334/1701026) – iRon Dec 31 '22 at 15:48

2 Answers2

1

You can use Get-Variable for this:

Get-Variable fruit, fruit2, fruit3 |
    Where-Object Value -NotContains Pears |
    ForEach-Object { '$' + $_.Name }

# Outputs: `$fruit`

What you should use instead as recommended in comments is a hash table:

$fruits = @{
    Fruits  = 'Apples','Oranges','Bananas'
    Fruits2 = 'Apples','Oranges','Bananas', 'Pears'
    Fruits3 = 'Apples','Oranges','Bananas', 'Pears'
}

$fruits.GetEnumerator().Where{ $_.Value -notcontains 'pears' }.Key

# Outputs: `Fruits`
Santiago Squarzon
  • 41,465
  • 5
  • 14
  • 37
1

Or using the variable: drive

dir variable:fruit* | ? value -notcontains pears

Name                           Value
----                           -----
fruit                          {Apples, Oranges, Bananas}
js2010
  • 23,033
  • 6
  • 64
  • 66