In the previous tip we illustrated how you can use Select-String to find lines in raw text containing a specific word. It took some effort to extract the actual value(s) representing a given pattern:
PS C:\> $data = ipconfig | select-string 'IPv4' PS C:\> [regex]::Matches($data,"\b(?:\d{1,3}\.){3}\d{1,3}\b") | Select-Object -ExpandProperty Value 192.168.2.112
This effort is not necessary, though, because Select-String is already using a regular expression match, and returns match objects.
PS C:\> ipconfig | Select-String '\b(?:\d{1,3}\.){3}\d{1,3}\b' | Select-Object -Property * IgnoreCase : True LineNumber : 16 Line : IPv4 Address. . . . . . . . . . . : 192.168.2.112 Filename : InputStream Path : InputStream Pattern : \b(?:\d{1,3}\.){3}\d{1,3}\b Context : Matches : {192.168.2.112} IgnoreCase : True LineNumber : 17 Line : Subnet Mask . . . . . . . . . . . : 255.255.255.0 Filename : InputStream Path : InputStream Pattern : \b(?:\d{1,3}\.){3}\d{1,3}\b Context : Matches : {255.255.255.0} IgnoreCase : True LineNumber : 19 Line : 192.168.2.1 Filename : InputStream Path : InputStream Pattern : \b(?:\d{1,3}\.){3}\d{1,3}\b Context : Matches : {192.168.2.1}
So you can use a simple Where-Object with the -like operator to do pre-filtering, identifying only the lines you are after (i.e. the ones containing the word “IPv4”), then submit a RegEx pattern to Select-String, and evaluate the results:
PS C:\> ipconfig | # do raw prefiltering and get only lines containing this word Where-Object { $_ -like '*IPv4*' } | # do RegEx filtering using a pattern for IPv4 addresses Select-String '\b(?:\d{1,3}\.){3}\d{1,3}\b' | # get the matching values Select-Object -ExpandProperty Matches | # get the value for each match Select-Object -ExpandProperty Value 192.168.2.112