Home > Back-end >  PowerShell, select the variable that is missing a value
PowerShell, select the variable that is missing a value

Time:12-31

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?

CodePudding user response:

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`

CodePudding user response:

Or using the variable: drive

dir variable:fruit* | ? value -notcontains pears

Name                           Value
----                           -----
fruit                          {Apples, Oranges, Bananas}
  • Related