Check if value exists in CSV

I’m either going about this very wrong or missing something very simple :slight_smile:

I’m trying to check a CSV file to see if a value exists, if it does i want to display a message to say it already exists otherwise say it doesn’t exist.

The issue i’m facing is it always tells me it doesn’t exist because as it loops through all the rows looking to see if the value is there, unless the value im looking for is the last entry in the CSV it always says it doesn’t exist because it ultimatley doesn’t equal the last entry.

$value = $textboxValue.Text
	
	foreach ($row in $csv)
	{
		if ($row.sku -eq $value)
		{
			$outputrichtextboxResult.Text = "Value Exists"
		}
		else
		{
			$outputrichtextboxResult.Text = "Value Doesn't Exist"
		}
	}

I guess my problem is im looking at each row one at a time rather than just asking if it exists in the file as a whole but i seem i have hit a mental block on something so seamingly simple.

I have searched online and not managed to find the answer either (well i probably did and just didn’t realise :slight_smile: ).

Any help will be greatly appreciated.

Cheers,
Jamie

You don’t need the foreach loop:

    if ($value -in $csv.sku) {
    
        $outputrichtextboxResult.Text = "Value Exists"
	
    }
		
    else {

        $outputrichtextboxResult.Text = "Value Doesn't Exist"

    }
1 Like

Thank you so much, i’ve done so many for loops when itterating through files to do {x, y, z} with them i just defaulted to that process :slight_smile:

I’ve never actually just asked a file if a value exists somewhere in there.

That works perfect thank you :slight_smile:

No problem. A loop is a perfectly valid way of approaching this and often will be required for working with files. If the value could appear in any column in the row, for example, then a loop may well be a better approach for that kind of search.

In this case though, as you’re only working with one column, you can simply check if the value is in the collection (array) of objects.

Technically, there is still a loop in there, it is just implicit vs explicit. When you do $csv.sku, Powershell is performing a loop like this to generate the array:

$csv | foreach{$_.sku}
1 Like