0

Objective: Compare the strings stored in $a with strings stored in $b. If strings exist in $b that do not exist in $a, display those.

  1. I'm running the following to search text files for certain information:

    $a = Select-String -Path *.txt "<string>"
    

    This returns lines containing the names of the text files (which are named after the servers they come from), the line number the string is found on, and the string itself. It stores it in the $a variable.

  2. I run the following to store a list of server names in variable $b:

    $b = Get-Content servers.txt
    
  3. I run the following to compare the contents of $a with $b, and tell me if there are any in the list in $b that are not contained in $a:

    $b | Where-Object {$a -NotMatch $_}
    

    I'm clearly doing something wrong, because this simply displays the contents of $a. Any ideas of how I can accomplish my objective?

briantist
  • 45,546
  • 6
  • 82
  • 127

1 Answers1

1

Select-String does not return lines. It may display that way, but what it really returns is a MtachInfo object containing properties with specific information about the match.

So what you really want to do is look at the .Filename property of each of the the match objects, which will be something like SERVERNAME.txt (if I understand your explanation correctly) and compare it to the server names in $b which I understand to be in the form SERVERNAME.

There are several ways you could do it, but because both sides are arrays, it would help a lot if you normalized them first:

$e = $a.Filename | ForEach-Object {
    $_ -replace '\.txt$',''  # trim off the extension
}
$b | Where-Object { $_ -notin $e }

This example works on PowerShell v3+.

To do it in v2 and below:

$e = $a | ForEach-Object {
    $_.Filename -replace '\.txt$',''
}
$b | Where-Object { $e -notcontains $_ }
briantist
  • 45,546
  • 6
  • 82
  • 127
  • Thank you for such a quick response! I'm using PSv5. I tried the first solution, and unfortunately, $e is empty. – user1690152 May 12 '16 at 23:54
  • Thank you. This one also displayed the contents of $b, leading me to think it runs and believes that all of the items in $b are missing from $a. – user1690152 May 13 '16 at 05:47