PowerTip: Get Row from CSV File Based On Value

Summary: Use Windows PowerShell to get a row from a CSV file based on a specific value.

Hey, Scripting Guy! Question How can I use Windows PowerShell 4.0 to look up a specific row from a CSV file I imported into a variable?

Hey, Scripting Guy! Answer Use the Where method, and use a match pattern to search on a specific column and value, for example:

$topics = import-csv -Path C:\lit\Shakespeare.txt

$topics.Where({$PSItem.play -eq 'hamlet'}).topic

Comments (6)

  1. So the last ‘topic’ is the actual search topic right?

  2. Chen V says:

    Ed good show. But where and for each methods are not well documented.

  3. Salil says:

    What are the contents of the csv? Is play a header field in the csv?

  4. So that’s how it’s done… I usually do a group-object as hashtable and then select the one that matches…
    $lookup = $topics | group-object -AsHashTable -Property ‘play’
    But it’s not as flexible…


  5. Rattenborg says:

    Salil, the content of the csv file (Shakespeare.txt) can be seen in "Use PowerShell to Add Table to Word Doc and Email as Attachment"

  6. Aaron F. says:

    This doesn’t appear to be nearly as useful as it should, since I can’t seem to “set” the value of the property I retrieve.

    $CSV.Where({$PSItem.Name -eq “John”}).UserName = “John111”
    The property ‘UserName’ cannot be found on this object. Verify that the property exists and can be set.
    At line:1 char:1

    But if I do the “old” syntax, it works fine:
    ( $CSV | ? { $_.Name -eq “John” } ).UserName = “John111”

    Am I doing something wrong, or is this just a limitation of how the Where() method works?

Skip to main content