Find lines in one Object based on strings in other object

90 Views Asked by At

Finding lines in one file based on rows in another file.

I have one object $A with some rows like:

0c7d3283-bec2-4db1-9078-ebb79d21afdf
200bc957-26dd-4e8e-aa6e-00dc357c4ac2
218e0d2a-0e8b-4a68-8136-8f5dd749a614

I want to find matches in object $B for those rows and print the lines with the matches to an output file.

I've been trying for a week now (my first week in powershell :) ) I've come to:

$F = $B | ForEach-Object{ $A | Select-String -Pattern $_$ -AllMatches| Select-Object line } 

but this doesn't give me any returning results.

Who is willing to help me out?

1

There are 1 best solutions below

5
On BEST ANSWER

If you want to match your first Array, with something that should match part of a string in a second array you do something like the code below:

$A = @("0c7d3283-bec2-4db1-9078-ebb79d21afdf", "200bc957-26dd-4e8e-aa6e-00dc357c4ac2", "218e0d2a-0e8b-4a68-8136-8f5dd749a614")

$B = @("Something 0c7d3283-bec2-4db1-9078-ebb79d21afdf", "Something else 200bc957-26dd-4e8e-aa6e-00dc357c4ac2", "Something also e3df3978-beb7-4545-bc48-ff40d8453be1")

foreach ($Line in $A) {
    if($B -match $Line) {
        $B | Where-Object {$_ -match $Line}
    }
}

We first loop through all the lines in the first object, then compare if the line is matched to anything in the second array. If we find a match we go through Array B to find where the Line from A matches.

You could make this code a hell lot prettier, but this the most understandable way I can write it.

Old Answer
You could use the Compare-Object cmdlet to compare the two arrays, then use the -IncludeEqual switch to show where there are matches and then use the -ExcludeDifferent switch to remove the results that do not match. Then take that Output and put in in a file. A simple test could be something like this:

$A = @("0c7d3283-bec2-4db1-9078-ebb79d21afdf", "200bc957-26dd-4e8e-aa6e-00dc357c4ac2", "218e0d2a-0e8b-4a68-8136-8f5dd749a614")

$B = @("0c7d3283-bec2-4db1-9078-ebb79d21afdf", "200bc957-26dd-4e8e-aa6e-00dc357c4ac2", "e3df3978-beb7-4545-bc48-ff40d8453be1")


(Compare-Object -ReferenceObject $A -DifferenceObject $B -ExcludeDifferent -IncludeEqual).InputObject | Out-File .\output.txt

This should output a file in your Shells current working directory with the two GUIDs that match:

0c7d3283-bec2-4db1-9078-ebb79d21afdf
200bc957-26dd-4e8e-aa6e-00dc357c4ac2

Where the one that didn't match is not included.