Anyway I can have my output only search for the last line of each string that I search for?

$String1 = "Oatmeal"
$String2 = "Cake"
$String1Location = "C:\1.txt"

try {
    Select-String -Path $String1Location -Pattern $String1, $String2 -ErrorAction Stop 
}

catch {
    return ""
}

My output is something like this:

C:\1.txt:4:Oatmeal
C:\1.txt:6:Cake
C:\1.txt:9:Cake
C:\1.txt:10:Oatmeal

But I only want to see

C:\1.txt:9:Cake
C:\1.txt:10:Oatmeal

Thanks in advance.

4 Answers

0
skimad On

How about if you do the following in your try block.

$found1=Select-String -Path $String1Location -Pattern $String1 -ErrorAction Stop 
$found1[-1]
$found2=Select-String -Path $String1Location -Pattern $String2 -ErrorAction Stop 
$found2[-1]
0
Dude be PSing On

This is what I ended up with and it is working:

try {
    Select-String -Path $String1Location -Pattern $String1 -ErrorAction Stop | Where-Object {$_ -match $String1} | Select-Object -Last 1
    Select-String -Path $String1Location -Pattern $String2 -ErrorAction Stop | Where-Object {$_ -match $String2} | Select-Object -Last 1
}
0
Theo On

I would suggest this:

$String1 = "Oatmeal"
$String2 = "Cake"
$String1Location = "C:\1.txt"

Select-String -Path $String1Location -Pattern $string1, $string2 -SimpleMatch | Group-Object Line | ForEach-Object {
    $_.Group | Sort-Object LineNumber | Select-Object -Last 1
}

Or by using a Regex match

$StringsToSearch = "Oatmeal","Cake"
$String1Location = "C:\1.txt"

# build the regex
$pattern = '\b(' + (($StringsToSearch | ForEach-Object { [regex]::Escape($_) }) -join '|') + ')\b' 
# this ends up in '\b(Oatmeal|Cake)\b' which means we are looking for these strings as whole string.
# if you also would like to search for strings that contain the search criteria, like 'Pancake',
# then use 
# $pattern = ($StringsToSearch | ForEach-Object { [regex]::Escape($_) }) -join '|'

Select-String -Path $String1Location -Pattern $pattern | Group-Object Line | ForEach-Object {
    $_.Group | Sort-Object LineNumber | Select-Object -Last 1
}

Note: If you want your output to be sorted on the Line number in ascending order, simply add | Sort-Object LineNumber after the last closing curly bracket.

0
LotPings On

The most simple solution is IMO to append | Sort-Object Pattern -Unique
and if neccessary to | Sort-Object LineNumber to have the original order.

$String1 = "Oatmeal"
$String2 = "Cake"
$String1Location = "C:\1.txt"

try {
    Select-String -Path $String1Location -Pattern $String1, $String2 -ErrorAction Stop |
       Sort-Object Pattern -Unique | Sort-Object LineNumber
}

catch {
    return ""
}