Powershell – Using PowerShell switch command with changing values

powershell

I am trying to use the switch command to select something out of an array. The array can change sizes depending on information from another spread sheet.

For example:

C:\> $Test = A
C:\> $ListA
    Item_One       Item_Two
    --------       --------
    A              1
    B              2
    C              3

I want to create a switch that will return the corresponding value of Item_Two when $Test is checked against $ListA.Item_One. The problem I am having is, $ListA can change the number of values depending on the situation. The switch statement I was thinking was something like this:

switch ($Test)
{
    $ListA.Item_One {write-host $ListA.Item_two}
    default {"Not found"}
}

When I run this code, it just ends up on the default, I can't get it to trigger off the $ListA.Item_One section. Is there a way to do this, or how else can I do what I'm trying to do? I know I can use a for-each loop, but I looking to see if there were other ways. I could imagine if the list got to large, it would take a long time to sift through. Right now the list is only 5-10 items, but it could grow to over 40+ within a year.

Edit: I am populating the list through a .csv:

$listA = Import C:\File.csv

Best Answer

With what you've done, $listA has no element named "Item_One" so that expression is effectively NULL
It's an array, and if you want to get "A" out of $listA, you need to use $listA[0].Item_One and $ListA[0].Item_two
Without knowing more about this situation not quite sure what to suggest...
Do you really have so many items you need a CSV?
If not try a hash table

PS C:\temp> $listA = import-csv .\list.csv
PS C:\temp> $listA

Item_One                                Item_Two
--------                                --------
A                                       1
B                                       2
C                                       3


PS C:\temp> $listA.gettype()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Object[]                                 System.Array


PS C:\temp> $listA.Item_One

PS C:\temp> $listA[0].Item_One
A

PS C:\temp> switch ($Test)
>> {
>> $listA[0].Item_One {write-host $ListA[0].Item_two}
>> default {"Not found"}
>> }
>>
1

# Hash table example
$hash=@{"A"=1;"B"=2;"C"=3}
$hash.A
1

New after Nick's 7/9 comment:

I don't think the case/switch structure is a good fit for this case. This seems like it will do what you need.

$listA | foreach {
    if ($_.item_one -eq "A") {
        # do something
        write-host $_.item_two
    } elseif ($_.item_one -eq "B") {
        # do something different
        write-host $_.item_two
    } else {
        $found = $false
    }
}
if ($found -eq $false) {
    write-host "default"
}

Depending on your needs, the IF clause could also be begin like this

if ($_.item_one -match "A|B|C") {