-2

I used the below steps to retrieve a string from file

$variable = 'abc@yahoo.com'
$test = $variable.split('@')[0];
$file = Get-Content C:\Temp\file1.txt | Where-Object { $_.Contains($test) }
$postPipePortion = $file | Foreach-Object {$_.Substring($_.IndexOf("|") + 1)}

This results in all lines that contain $test as a substring. I just want the result to contain only the lines that exactly matches $test.

For example, If a file contains

abc_def|hf#23$ 
abc|ohgvtre

I just want the text ohgvtre

Ryan Bemrose
  • 9,018
  • 1
  • 41
  • 54
Cooluser
  • 11
  • 2
  • I don't follow you. Why bother splitting the string at all then? Why not just search for 'abc@yahoo.com`? – Jason Boyd Jun 29 '16 at 18:49
  • 1
    @briantist Not a duplicate. [That question](http://stackoverflow.com/questions/18877580/powershell-and-the-contains-operator) is about the operator, which doesn't work on characters in strings. This one correctly uses the .NET `String.Contains` method to compare substrings. The problem is that OP wants an exact match, not a substring match, so both forms of "contains" are wrong. – Ryan Bemrose Jul 09 '16 at 21:51
  • @RyanBemrose you're right; I've retracted my close vote. – briantist Jul 09 '16 at 23:23

2 Answers2

1

If I understand the question correctly you probably want to use Import-Csv instead of Get-Content:

Import-Csv 'C:\Temp\file1.txt' -Delimiter '|' -Header 'foo', 'bar' |
  Where-Object { $_.foo -eq $test } |
  Select-Object -Expand bar
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
1

To address the exact matching, you should be testing for equality (-eq) rather than substring (.Contains()). Also, there is no need to parse the data multiple times. Here is your code, rewritten to to operate in one pass over the data using the -split operator.

$variable = 'abc@yahoo.com'
$test = $variable.split('@')[0];

$postPipePortion = (

  # Iterate once over the lines in file1.txt
  Get-Content C:\Temp\file1.txt | foreach {

    # Split the string, keeping both parts in separate variables.
    # Note the backslash - the argument to the -split operator is a regex
    $first, $second = ($_ -split '\|')

    # When the first half matches, output the second half.
    if ($first -eq $test) {
      $second
    }
  }
)
Ryan Bemrose
  • 9,018
  • 1
  • 41
  • 54