powershellmultilineselect-string

Powershell / Find whole line by matching pattern in variable


How can I return whole line by matching pattern from variable?

Have below code to write particular events to variable:

$date = (get-date).AddDays(-1)
$log = Get-WinEvent -FilterHashtable @{ LogName='Security'; StartTime=$Date; Id='6416'}

If accessing particular event message:

$log[0].Message

Return text is:

Device ID:  SWD\\MMDEVAPI\\{0.0.1.00000000}
Device Name:    Headset
Class ID:       {.......}
Class Name: AudioEndpoint

How can I get whole line by matching pattern "Class Name:"?

Need to get below output

Class Name: AudioEndpoint

Tried below command but it returns the same whole content:

select-string -Pattern "Class Name:" -InputObject $log[0].Message

Solution

  • In PowerShell (Core) 7 (the modern, cross-platform, install-on-demand edition):

    $log[0].Message -split '\r?\n' | 
      Select-String -Raw -Pattern "Class Name:" 
    

    In Windows PowerShell (the legacy, ships-with-Windows, Windows-only edition of PowerShell whose latest and last version is 5.1):

    $log[0].Message -split '\r?\n' | 
      Select-String -Pattern "Class Name:" | 
      ForEach-Object Line
    


    [1] Note that while pipeline input ultimately also binds to the -InputObject parameter, the latter's purpose is to merely facilitate pipeline input, as an implementation detail. To wit, because this parameter is defined as [psobject] in this case, you can not meaningfully pass multiple input strings to it by argument (e.g.,
    -InputObject 'line 1', 'line 2'), as that would result in those strings getting joined with spaces to form a single input string.
    For more information, see GitHub issue #4242.