Search code examples
powershellcsvif-statementpowershell-3.0verification

Check CSV for object not matching?


Probably a really elementary question but preliminary searches didn't return much. I'm writing a script that takes $CSC (which is user input) compares it to a .csv object called "CSC" and then populates the relevant information based off that.

$CSC = "1100 4WWW"   #Hardcoded value to test against #CSC are always <#### #ChChCh>
$roster = Import-Csv <my path>

Foreach ($row in $roster) {
    If ($CSC -eq $row.CSC) { 
        $Department = $row.Department
        $Division = $row.Division
        $Street = $row.Street
        $City = $row.City
        $State = $row.State
        $Zipcode = $row.Zipcode
        $OfficePhone = $row.Phone
        $Country = $row.Country
    } Else {    }
}

That's working fine but how would I check if a user input $CSC didn't match an in the list?

Making the else or making an elseif ($CSC -ne $row.CSC) obviously returns a value for every line except the matching one. I'm guessing I should use a nested if statement but being self taught I wasn't sure what the best way to do this is. Thanks.


Solution

  • I can think of a couple things you can do.

    Option 1: Using the -match operator. [not recommended as it has some regex constraints but I will present it as an option anyway]

    $CSC = "1100 4WWW"   #Hardcoded value to test against #CSC are always <#### #ChChCh>
    $roster = Import-Csv <my path>
    
    if ($roster -match $CSC)
    {
        Foreach ($row in $roster) {
            If ($CSC -eq $row.CSC) { 
                $Department = $row.Department
                $Division = $row.Division
                $Street = $row.Street
                $City = $row.City
                $State = $row.State
                $Zipcode = $row.Zipcode
                $OfficePhone = $row.Phone
                $Country = $row.Country
            } Else {    }
        }
    }
    else
    {
       #your 'not a match' code goes here
    }
    

    Option 2: Set a flag

    $CSC = "1100 4WWW"   #Hardcoded value to test against #CSC are always <#### #ChChCh>
    $roster = Import-Csv <my path>
    
    $flag = $false
    Foreach ($row in $roster)
    {
        If ($CSC -eq $row.CSC)
        { 
            $Department = $row.Department
            $Division = $row.Division
            $Street = $row.Street
            $City = $row.City
            $State = $row.State
            $Zipcode = $row.Zipcode
            $OfficePhone = $row.Phone
            $Country = $row.Country
    
            $flag = $true
        }
        Else {    }
    }
    
    If (!$flag)
    {
        #your 'not a match' code goes here
    }