PowerShell script to show file location and line number which match patterns?

People,

Can anyone here please assist me in modifying the below PowerShell script to list the line number where the certain pattern is matched?

$inFile = '\\server\share\directory\file.txt' $outFile = '\\server\share\directory\result.txt' $patternFile = 'C:\Temp\patternlist.txt'

$pattern = (Get-Content -Path $patternFile | ForEach-Object {[regex]::Escape($_)}) -join ‘|’
Write-Host “Searching with pattern ‘$($pattern)’”
Select-String -Path $inFile -Pattern $pattern | Select-Object -ExpandProperty Line | Set-Content -Path $outFile


The above script works but the exported file does not have the line number column where I can find the matched pattern?

Thanks in advance.

You could literally do this all in a one-liner

gci C:\temp | select-string -Pattern 'balloon|hello' | select @{n='Filename';e={$_}},LineNumber

Filename                                                                                       LineNumber
--------                                                                                       ----------
C:\temp\HelloWorld.ps1:1:'hello world'                                                                  1
C:\temp\task.ps1:2:        $balloon = [System.Windows.Forms.NotifyIcon]::new()                          2
C:\temp\task.ps1:4:        $balloon.Icon = [System.Drawing.Icon]::ExtractAssociatedIcon($path)          4
C:\temp\task.ps1:5:        $balloon.BalloonTipIcon  = [System.Windows.Forms.ToolTipIcon]::Info          5
C:\temp\task.ps1:6:        $balloon.BalloonTipTitle = 'test'                                            6
C:\temp\task.ps1:7:        $balloon.BalloonTipText  = 'testing'                                         7
C:\temp\task.ps1:8:        $balloon.Visible  = $true                                                    8
C:\temp\task.ps1:9:        $balloon.ShowBalloonTip(15000)                                               9
C:\temp\task.ps1:10:        $balloon.dispose()                                                         10