Powershell grep output

Powershell grep output DEFAULT

Adam the Automator

TwitterFacebookLinkedIn

One of the first Linux commands that many system administrators learn is grep. This venerable tool has been around for decades and is crucial to any administrator’s toolbelt. Grep’s core is simply the ability to search plain text for a RegEx pattern. Grep can search files in a given directory or streamed input to output matches. Did you know PowerShell has grep? Well..almost.

PowerShell, being a language, is more than just a single purpose binary. Therefore what built-in abilities exist to search for plain text using RegEx patterns much like grep does? In this article we explore the myriad ways to search for text in files using PowerShell.

Exploring the Cmdlet

(our PowerShell grep) works on lines of text and by default will looks for the first match in each line and then displays the file name, line number, and the text within the matched line. Additionally, can work with different file encodings, such as Unicode text, by use the byte-order-mark (BOM) to determine the encoding format. If the BOM is missing, will assume it is a UTF8 file.

Parameters of

  • – Normally, will only look for the first match in each line, using this parameter the cmdlet will search for more than one match. A single object will still be emitted for each line, but it will contain all of the matches found.
  • – Matches are not case-sensitive by default, this forces the cmdlet to look for matches that match exactly to the input pattern.
  • – A very useful parameter in that, you can define the number of lines before and after the match that will be displayed. Adding this parameter modifies the emitted object to include a new property that contains the lines specified.

Keep in mind that if you pipe the output of to another call, the context won’t be available since you are only searching on the single resulting property.

  • – Used with the parameter, this specifies a culture to be matched with the specified pattern. This includes options such as , , or as examples. A few other useful options is the and options. is for non-linguistic binary comparisons and is for culture independent comparisons.

This parameter was introduced in PowerShell 7 and is not available to prior versions. Also keep in mind that this will use the current culture of the system, by default, which can be found using .

  • – Specify the encoding of the target file to search, which a default of .
    • : Uses the encoding for the ASCII (7-bit) character set.
    • : Encodes in UTF-16 format using the big-endian byte order.
    • : Uses the default encoding for MS-DOS and console programs.
    • : Encodes in UTF-16 format using the little-endian byte order.
    • : Encodes in UTF-7 format.
    • : Encodes in UTF-8 format.
    • : Encodes in UTF-8 format with Byte Order Mark (BOM)
    • : Encodes in UTF-8 format without Byte Order Mark (BOM)
    • : Encodes in UTF-32 format.
    Starting with PowerShell Core 6.2, the parameter also accepts numeric IDs of registered code pages such as or string names such as .

Starting with PowerShell Core 6.2, the parameter also accepts numeric IDs of registered code pages such as or string names such as .

  • – Working with the parameter, exclude specific items using a pattern, such as .
  • – Just like the parameter, will include only the specified items using a pattern, such as .
  • – Only return the first instance of matching text from each input file. This is intended to be a fast and efficient way to retrieve a listing of files that have matching contents.
  • – This tells to use the values as input, instead of interpreting values such as as a wildcard. If the path includes escape characters, enclose them in single quotation marks to do no interpretation.
  • – Instead of highlighting the string that the pattern is matched upon, disable the highlighting of matches. By default, emphasis uses negative colors based on the background text colors.
  • – Look for text that does not match the specified pattern.
  • – Specify the path to the files to search. Wildcards are permitted, but you cannot specify only a directory. The default is the local directory.
  • – The pattern to search the input content or files for based on RegEx.
  • – Use a simple match instead of regular expressions. Since RegEx is not used, the returned object does not have any values in the property.
  • – Output the matching strings, without a object. This is the behavior that is most similar to and not the more object oriented nature of PowerShell.
  • – Only return a or if the pattern is found.

Using PowerShell Grep err…

Of course knowing how the parameters and options of a cmdlet work is not quite the same as using it in a production environment. Let’s dive into examples and see how we can leverage to make find text matches easier.

There are three ways that we can use to find matches.

  • Pipe in quoted text to the cmdlet, i.e. stream in the text.
  • Using text stored in a variable, pass the variable to the parameter.
  • Use the parameter to specify files to search for the text in.

The files we are using for testing this are randomly generated content, but of the same type as often found in production systems.

Simple Matching in Files

Starting off with a very simple example, let us look for in a handful of CSV files.

Demonstrating a simple Select-String pattern match.

As you can tell, this is pretty simple, we see how is highlighted on the line with the rest of the data. But what data is actually being returned here? Let us take a look at all of the properties of a returned match.

Showing the returned properties from a Select-String match.

We have a couple of properties here that are useful. Notably the , , , and . Most of what we want to know is in the property.

Enumerating the Matches property and available data.

Here you can see how even though we used a simple expression, this is still a RegEx expression and the subsequent details available.

What if we look for several different values using comma separated patterns? This is useful as this actually defines three different patterns and not one complex RegEx value.

Returning multiple matches from a Select-String search.

You can see how this is the case, if we select only the , , and from our search.

Filtering the results from a multiple Select-String match.

More Complex RegEx Matching

Now that we demonstrated some of the simpler matching methods, what about utilizing RegEx more to actually look for more useful patterns? The three examples here are looking for Email Addresses, IP Addresses, and Social Security Numbers (SSNs). The patterns used here are not the only way to construct a RegEx search, and there may be easier ways. PowerShell Grep (Select-String) is a pretty advanced cmdlet.

Let’s look to see if emails are contained in our files. Using a somewhat complex RegEx match, as shown below, will demonstrate finding those matches.

Demonstrating using RegEx to match data.

Of course, of more concern might be if there were SSNs included in a file. A very simple match for this would be the following.

Demonstrating a simple SSN RegEx search.

Finally, what if we wanted to look up some IP Addresses in our file? Using another RegEx expression to look for that pattern, makes quick work.

Demonstrating a simple IP Address RegEx search.

A caveat about this RegEx. Technically, this will match values up to which is an invalid IP. You can construct more accurate RegEx expressions that will get longer, but it is a trade off depending on what you are looking to do.

Searching with Context

Context is very useful in troubleshooting, it helps to explain what is happening prior to an event occurring and after. For example, let’s search in an Apache log and find this text.

Searching for a line in an Apache log.

The simple indicates the matched line, and there is one line prior to the match and after the match. In this example, this could tell us that the Google bot was looking for and unfortunately received a result instead. Next, it went to try the homepage and perhaps got the same error.

What exactly is contained in the property then as emitted by the object? If we expand upon that property, you can see that there is and . This means you can manipulate this further down the line if necessary.

Demonstrating the Context property.

Other examples of searching through log files are in articles such as Making Sense of the Microsoft DNS Debug Log which demonstrates using to look through a DNS debug log. The PowerShell grep is strong in that post.

Conclusion

Grep is an incredibly useful tool in the Linux world, and offers much of the same functionality in the PowerShell world. Adding in the object-oriented nature of PowerShell only serves to enhance the utility and usefulness that the cmdlet offers.

For many System Administrators, being able to quickly and efficiently search log files over varying types, along with understanding context, is an incredibly important and necessary ability. PowerShell makes this easy to do and saves countless hours of troubleshooting!

More from Adam The Automator & Friends

Related

Sours: https://adamtheautomator.com/powershell-grep/

The command in Linux is widely used for parsing files and searching for useful data in the outputs of different commands.

The command is a Windows equivalent in a Windows command-line prompt (CMD).

In a Windows PowerShell the alternative for is the command.

Below you will find some examples of how to “grep” in Windows using these alternatives.

Grep Command in Windows

Grep the output of a command for a specific port:

# Windows CMD C:\> netstat -na | findstr "PORT" # Windows PowerShell PS C:\> netstat -na | Select-String "PORT"

If a command in PowerShell returns some objects, before parsing, they should be converted to strings using the command:

# Windows PowerShell PS C:\> Get-Alias | Out-String -Stream | Select-String "curl"

Grep a file for a pattern that matches a regular expression (case insensitive):

# Windows CMD C:\> findstr /i "^SEARCH.*STRING$" file.txt # Windows PowerShell PS C:\> Select-String "^SEARCH.*STRING$" file.txt

Display for the Windows command equivalents:

# Windows CMD C:\> findstr /? # Windows PowerShell PS C:\> get-help Select-String
Sours: https://www.shellhacks.com/windows-grep-equivalent-cmd-powershell/
  1. Cello chords
  2. Cno guidance
  3. Tampa kawasaki
  4. Canvas pencil cases bulk

How to Grep in PowerShell:

Here’s some example commands in PowerShell to replicate Grep:

  • Get-Process | Where-Object {$_ | Select-String “foo”}
  • get-process | where ProcessName -like “*foo*
  • get-process | findstr foo
  • ps *foo*

Applies To : PowerShell


For those who have lived in the Linux/Unix command line, the ‘grep‘ command is a commonly used way of finding something that you want in a chunk of data.

Øyvind Kallstad did a great writeup of comparing a bunch of ways to use PowerShell instead of grep which is worth reading.

The article covers a bunch of scenarios, and is centered around starting with the ‘grep’ command and working with it. However, there’s the other common use case of running a different command, then piping those results to grep to search for something.

This blogpost was triggered by Janet who asked me this fair question:

As with poor cute cats, there’s more than one way to skin PowerShell.

I had to do some research and asking around on this, because normally I’d filter out the property of the object I was looking at, and work with that. Using the get-process example:

get-process | where ProcessName -like "*foo*

That works, but it’s still a lot clunkier than what a grep user would expect. An easier way would be to use the ‘findstr‘ program (which also has a bunch of useful swtiches):

get-process | findstr foo

I say program because ‘findstr’ is not a PowerShell cmdlet, but it’s still native to Windows and works perfectly fine. It’s case sensitive though, so you need to use -i for case insensitive results.

That’s great for simple stuff, but we’re sort of breaking what PowerShell does. You’re no longer dealing with a standard PowerShell object, so further piping and processing won’t really work.

The ‘proper’ PowerShell way would be to use the ‘Where-Object’ command:

Get-Process | Where-Object {$_ | Select-String "foo"}

A bit longer, but you can shorten ‘Where-Object’ to ‘Where’. Although more involved, it’s good to get into the habit of doing it this way, so when you’re piping this to the next command, it still says as a standard object that can be read and manipulated.’

(Update 24th Feb 2017) As Steve_N points out in the comments section, there’s a much shorter way of doing this:

ps *foo*

That’s it. Many PowerShell commands have inbuilt aliases, including ‘get-process’. You can see what this is with the command ‘get-alias -definition get-process’

This shows that ‘gps’ and ‘ps’ are both aliases to the command  ‘get-process’. You can also create your own aliases with the ‘set-alias‘ command.

The ‘*foo*’ part works because the command assumes the -name switch has been used, which lets you define what criteria to search and show in the ProcessName field. This is the same way that many commands don’t need the -identity switch used, because it’s written to assume you’re going to tell it what identity/username/upn to work with.

This can also be piped to something else, so it’s a winner. It’s less ideal for scripts though, because it’s much harder to read, and you can’t assume that everyone will know the short alias of a full command.

Also note that this isn’t grep related at all, so part of the answer to the original question is that you may not even need grep or select-string as it adds unnecessary overhead of getting data and parsing it, whereas this updated example filters the data as it’s obtained.

(Update ends)

PowerShell isn’t a Linux/Unix command line, but Microsoft have incorporated many of the concepts from bash. If you still can’t bear to use PowerShell on Windows, there’s always the Linux Bash Shell on Windows.

Thanks again to Steve Mclnerey for the grep advice :)

Other Blog Posts

Sours: https://www.adamfowlerit.com/2017/02/how-to-grep-in-powershell/
Working with CSV's in Windows Powershell

PowerShell: how to grep command output?

I think this solution is easier and better, use directly the function findstr:

You can also make an alias to use grep word:


Your problem is that alias emits a stream of AliasInfo objects, rather than a stream of strings. This does what I think you want.

or as a function

When you don't handle things that are in the pipeline (like when you just ran 'alias'), the shell knows to use the ToString() method on each object (or use the output formats specified in the ETS info).


If you truly want to "grep" the formatted output (display strings) then go with Mike's approach. There are definitely times where this comes in handy. However if you want to try embracing PowerShell's object pipeline nature, then try this. First, check out the properties on the objects flowing down the pipeline:

Note the Definition property which is a header you see when you display the output of Get-Alias (alias) e.g.:

Usually the header title matches the property name but not always. That is where using Get-Member comes in handy. It shows you what you need to "script" against. Now if what you want to "grep" is the Definition property contents then consider this. Rather than just grepping that one property's value, you can instead filter each AliasInfo object in the pipepline by the contents of this property and you can use a regex to do it e.g.:

In this example I use the Where-Object cmdlet to filter objects based on some arbitrary script. In this case, I filter by the Defintion property matched against the regex 'alias'. Only those objects that return true for that filter are allowed to propagate down the pipeline and get formatted for display on the host.

BTW if you're typing this, then you can use one of two aliases for Where-Object - 'Where' or '?'. For example:

Sours: https://newbedev.com/powershell-how-to-grep-command-output

Output powershell grep

The grep command is widely used on Linux to parse files and shell output. Using grep you can easily find and filter the output returned by the previous command in the pipeline. In this article, we’ll take a look at the equivalents of the grep command in Windows PowerShell.

On the Windows Command Line (CMD), the equivalent to grep is findstr. However, it is difficult to use it in PowerShell scripts. The simplest PowerShell equivalent to grep is Select-String.

The Select-String cmdlet provides the following features:

  • Search by regular expressions (default);
  • Search by literal match (the parameter -Simple);
  • Search only the first match in the file, ignoring all subsequent ones (the –List switch);
  • Search for all matches, even if there are several of them in one line (-AllMatches);
  • Search for lines that don’t match the pattern (the –NotMatch parameter is similar to the –v switch of the grep tool);
  • In addition to the directly matched line, display several previous and next lines (the -Context argument);
  • Select-String allows specifying the encoding of the input file (parameter -Encoding). The following encodings are supported: ASCII, BigEndianUnicode, OEM, Unicode, UTF7, UTF8, UTF8BOM, UTF8NoBOM, UTF32.

For example, use the following command to find a list of open ports on your computer (with the Listening status):

netstat -na | Select-String "LISTENING"

powershell grep equivalent

If the previous pipe command returns objects rather than text, use the Out-String –Stream command before passing them to Select-String:

Get-Service | Out-String -Stream | Select-String "Running"

grep equivalent in powershell

You can use the regular expressions (RegEx) in the Select-String cmdlet. For example, the following command will find all files or lines containing the word “Error” in the specified folder:

Get-ChildItem -Path C:\PS | Select-String -Pattern 'Error'

If you need to check all sub-folders, use the -Recurse parameter:

Get-ChildItem "C:\PS\" -Filter *.log -Recurse | Select-String "Failed"|

To display the names of all found files and matching line numbers:

Get-ChildItem "C:\PS\" -Filter *.log -Recurse | Select-String "Failed"| Select Filename, LineNumber, Line, Path | Format-Table

grep powershell equivalent

You can copy all files with matches to the specified directory:

Get-ChildItem C:\logs\ -Filter *.log -Recurse | Select-String "Failed"| Copy-Item -Destination C:\Errors

As you can see, the Select-String cmdlet allows you to process string data. Use the Where-Object cmdlet if you need to grep objects (Filtering PowerShell objects using Where-Object).

For example, you want to find all processes that use more than 300 MB of RAM:

Get-Process | Where-Object { $_.WorkingSet -gt 314572800 }

windows grep equivalent

Cyril Kardashevsky

Cyril Kardashevsky

I enjoy technology and developing websites. Since 2012 I'm running a few of my own websites, and share useful content on gadgets, PC administration and website promotion.

Cyril Kardashevsky

Latest posts by Cyril Kardashevsky (see all)

Sours: https://theitbros.com/powershell-grep-equivalent/
How to grep in Powershell

Select-String

Finds text in strings and files.

Syntax

Description

The cmdlet searches for text and text patterns in input strings and files. You can use similar to grep in UNIX or findstr.exe in Windows.

is based on lines of text. By default, finds the first match in each line and, for each match, it displays the file name, line number, and all text in the line containing the match. You can direct to find multiple matches per line, display text before and after the match, or display a Boolean value (True or False) that indicates whether a match is found.

uses regular expression matching, but it can also perform a match that searches the input for the text that you specify.

can display all the text matches or stop after the first match in each input file. can be used to display all text that doesn't match the specified pattern.

You can also specify that should expect a particular character encoding, such as when you're searching files of Unicode text. uses the byte-order-mark (BOM) to detect the encoding format of the file. If the file has no BOM, it assumes the encoding is UTF8.

Examples

Example 1: Find a case-sensitive match

This example does a case-sensitive match of the text that was sent down the pipeline to the cmdlet.

The text strings Hello and HELLO are sent down the pipeline to the cmdlet. uses the Pattern parameter to specify HELLO. The CaseSensitive parameter specifies that the case must match only the upper-case pattern. SimpleMatch is an optional parameter and specifies that the string in the pattern isn't interpreted as a regular expression. displays HELLO in the PowerShell console.

Example 2: Find matches in text files

This command searches all files with the file name extension in the current directory. The output displays the lines in those files that include the specified string.

In this example, and are used with the cmdlet to create two text files in the current directory, Alias.txt and Command.txt.

uses the Path parameter with the asterisk () wildcard to search all files in the current directory with the file name extension . The Pattern parameter specifies the text to match Get-. displays the output in the PowerShell console. The file name and line number precede each line of content that contains a match for the Pattern parameter.

Example 3: Find a pattern match

In this example, multiple files are searched to find matches for the specified pattern. The pattern uses a regular expression quantifier. For more information, see about_Regular_Expressions.

The cmdlet uses two parameters, Path and Pattern. The Path parameter uses the variable that specifies the PowerShell directory. The remainder of the path includes the subdirectory en-US and specifies each file in the directory. The Pattern parameter specifies to match a question mark () in each file. A backslash () is used as an escape character and is necessary because the question mark () is a regular expression quantifier. displays the output in the PowerShell console. The file name and line number precede each line of content that contains a match for the Pattern parameter.

Example 4: Use Select-String in a function

This example creates a function to search for a pattern in the PowerShell help files. For this example, the function only exists in the PowerShell session. When the PowerShell session is closed, the function is deleted. For more information, see about_Functions.

The function is created on the PowerShell command line. The command uses the name . Press Enter to begin adding statements to the function. From the prompt, add each statement and press Enter as shown in the example. After the closing bracket is added, you're returned to a PowerShell prompt.

The function contains two commands. The variable stores the path to the PowerShell help files. is the PowerShell installation directory with the subdirectory en-US that specifies each file in the directory.

The command in the function uses the Path and Pattern parameters. The Path parameter uses the variable to get the path. The Pattern parameter uses the string About_ as the search criteria.

To run the function, type . The function's command displays the output in the PowerShell console.

Example 5: Search for a string in a Windows event log

This example searches for a string in a Windows event log. The variable represents the current object in the pipeline. For more information, see about_Automatic_Variables.

The cmdlet uses the LogName parameter to specify the Application log. The MaxEvents parameter gets the 50 most recent events from the log. The log content is stored in the variable named .

The variable is sent down the pipeline to the cmdlet. uses the InputObject parameter. The variable represents the current object and is a property of the event. The Pattern parameter species the string Failed and searches for matches in . displays the output in the PowerShell console.

Example 6: Find a string in subdirectories

This example searches a directory and all of its subdirectories for a specific text string.

uses the Path parameter to specify C:\Windows\System32*.txt. The Recurse parameter includes the subdirectories. The objects are sent down the pipeline to .

uses the Pattern parameter and specifies the string Microsoft. The CaseSensitive parameter is used to match the exact case of the string. displays the output in the PowerShell console.

Note

Dependent upon your permissions, you might see Access denied messages in the output.

Example 7: Find strings that do not match a pattern

This example shows how to exclude lines of data that don't match a pattern.

The cmdlet sends objects down the pipeline to the to create the Command.txt file in the current directory. uses the Path parameter to specify the Command.txt file. The Pattern parameter specifies Get and Set as the search pattern. The NotMatch parameter excludes Get and Set from the results. displays the output in the PowerShell console that doesn't include Get or Set.

Example 8: Find lines before and after a match

This example shows how to get the lines before and after the matched pattern.

The cmdlet sends objects down the pipeline to the to create the Command.txt file in the current directory. uses the Path parameter to specify the Command.txt file. The Pattern parameter specifies as the search pattern. The Context parameter uses two values, before and after, and marks pattern matches in the output with an angle bracket (). The Context parameter outputs the two lines before the first pattern match and three lines after the last pattern match.

Example 9: Find all pattern matches

This example shows how the AllMatches parameter finds each pattern match in a line of text. By default, only finds the first occurrence of a pattern in a line of text. This example uses object properties that are found with the cmdlet.

The cmdlet uses the Path parameter. The Path parameter uses the variable that specifies the PowerShell directory. The remainder of the path includes the subdirectory en-US and specifies each file in the directory. The objects are stored in the variable. The variable is sent down the pipeline to the cmdlet. uses the Pattern parameter to search each file for the string PowerShell.

From the PowerShell command line, the variable contents are displayed. There's a line that contains two occurrences of the string PowerShell.

The property lists the first occurrence of the pattern PowerShell on each line.

The property counts the first occurrence of the pattern PowerShell on each line.

The variable uses the same and cmdlets, but adds the AllMatches parameter. AllMatches finds each occurrence of the pattern PowerShell on each line. The objects stored in the and variables are identical.

The property increases because for each line, every occurrence of the pattern PowerShell is counted.

Parameters

-AllMatches

Indicates that the cmdlet searches for more than one match in each line of text. Without this parameter, finds only the first match in each line of text.

When finds more than one match in a line of text, it still emits only one MatchInfo object for the line, but the Matches property of the object contains all the matches.

Note

This parameter is ignored when used in combination with the SimpleMatch parameter. If you wish to return all matches and the pattern that you are searching for contains regular expression characters, you must escape those characters rather than using SimpleMatch. See about_Regular_Expressions for more information about escaping regular expressions.

Type:SwitchParameter
Position:Named
Default value:False
Accept pipeline input:False
Accept wildcard characters:False

-CaseSensitive

Indicates that the cmdlet matches are case-sensitive. By default, matches aren't case-sensitive.

Type:SwitchParameter
Position:Named
Default value:False
Accept pipeline input:False
Accept wildcard characters:False

-Context

Captures the specified number of lines before and after the line that matches the pattern.

If you enter one number as the value of this parameter, that number determines the number of lines captured before and after the match. If you enter two numbers as the value, the first number determines the number of lines before the match and the second number determines the number of lines after the match. For example, .

In the default display, lines with a match are indicated by a right angle bracket () (ASCII 62) in the first column of the display. Unmarked lines are the context.

The Context parameter doesn't change the number of objects generated by . generates one MatchInfo object for each match. The context is stored as an array of strings in the Context property of the object.

When the output of a command is sent down the pipeline to another command, the receiving command searches only the text in the matched line. The matched line is the value of the Line property of the MatchInfo object, not the text in the context lines. As a result, the Context parameter isn't valid on the receiving command.

When the context includes a match, the MatchInfo object for each match includes all the context lines, but the overlapping lines appear only once in the display.

Type:Int32[]
Position:Named
Default value:None
Accept pipeline input:False
Accept wildcard characters:False

-Culture

Specifies a culture name to match the specified pattern. The Culture parameter must be used with the SimpleMatch parameter. The default behavior uses the culture of the current PowerShell runspace (session).

To get a list of all supported cultures, use command.

In addition, this parameter accepts the following arguments:

  • CurrentCulture, that is default;
  • Ordinal, that is non-linguistic binary comparison;
  • Invariant, that is culture independent comparison.

With command you gets fastest binary comparison.

The Culture parameter uses tab completion to scroll through the list of arguments that specify the available cultures. To list all available arguments, use the following command:

For more information about .NET CultureInfo.Name property, see CultureInfo.Name.

The Culture parameter was introduced in PowerShell 7.

Type:String
Position:Named
Default value:Culture of the current PowerShell session
Accept pipeline input:False
Accept wildcard characters:False

-Encoding

Specifies the type of encoding for the target file. The default value is .

The acceptable values for this parameter are as follows:

  • : Uses the encoding for the ASCII (7-bit) character set.
  • : Encodes in UTF-16 format using the big-endian byte order.
  • : Encodes in UTF-32 format using the big-endian byte order.
  • : Uses the default encoding for MS-DOS and console programs.
  • : Encodes in UTF-16 format using the little-endian byte order.
  • : Encodes in UTF-7 format.
  • : Encodes in UTF-8 format.
  • : Encodes in UTF-8 format with Byte Order Mark (BOM)
  • : Encodes in UTF-8 format without Byte Order Mark (BOM)
  • : Encodes in UTF-32 format.

Beginning with PowerShell 6.2, the Encoding parameter also allows numeric IDs of registered code pages (like ) or string names of registered code pages (like ). For more information, see the .NET documentation for Encoding.CodePage.

Note

UTF-7* is no longer recommended to use. As of PowerShell 7.1, a warning is written if you specify for the Encoding parameter.

Type:Encoding
Accepted values:ASCII, BigEndianUnicode, BigEndianUTF32, OEM, Unicode, UTF7, UTF8, UTF8BOM, UTF8NoBOM, UTF32
Position:Named
Default value:UTF8NoBOM
Accept pipeline input:False
Accept wildcard characters:False

-Exclude

Exclude the specified items. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as . Wildcards are permitted.

Type:String[]
Position:Named
Default value:None
Accept pipeline input:False
Accept wildcard characters:True

-Include

Includes the specified items. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as . Wildcards are permitted.

Type:String[]
Position:Named
Default value:None
Accept pipeline input:False
Accept wildcard characters:True

-InputObject

Specifies the text to be searched. Enter a variable that contains the text, or type a command or expression that gets the text.

Using the InputObject parameter isn't the same as sending strings down the pipeline to .

When you pipe more than one string to the cmdlet, it searches for the specified text in each string and returns each string that contains the search text.

When you use the InputObject parameter to submit a collection of strings, treats the collection as a single combined string. returns the strings as a unit if it finds the search text in any string.

Type:PSObject
Position:Named
Default value:None
Accept pipeline input:True
Accept wildcard characters:False

-List

Only the first instance of matching text is returned from each input file. This is the most efficient way to retrieve a list of files that have contents matching the regular expression.

By default, returns a MatchInfo object for each match it finds.

Type:SwitchParameter
Position:Named
Default value:False
Accept pipeline input:False
Accept wildcard characters:False

-LiteralPath

Specifies the path to the files to be searched. The value of the LiteralPath parameter is used exactly as it's typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell PowerShell not to interpret any characters as escape sequences. For more information, see about_Quoting_Rules.

Type:String[]
Aliases:PSPath, LP
Position:Named
Default value:None
Accept pipeline input:True
Accept wildcard characters:False

-NoEmphasis

By default, highlights the string that matches the pattern you searched for with the Pattern parameter. The NoEmphasis parameter disables the highlighting.

The emphasis uses negative colors based on your PowerShell background and text colors. For example, if your PowerShell colors are a black background with white text. The emphasis is a white background with black text.

This parameter was introduced in PowerShell 7.

Type:SwitchParameter
Position:Named
Default value:False
Accept pipeline input:False
Accept wildcard characters:False

-NotMatch

The NotMatch parameter finds text that doesn't match the specified pattern.

Type:SwitchParameter
Position:Named
Default value:False
Accept pipeline input:False
Accept wildcard characters:False

-Path

Specifies the path to the files to search. Wildcards are permitted. The default location is the local directory.

Specify files in the directory, such as , , or . If you specify only a directory, the command fails.

Type:String[]
Position:1
Default value:Local directory
Accept pipeline input:True
Accept wildcard characters:True

-Pattern

Specifies the text to find on each line. The pattern value is treated as a regular expression.

To learn about regular expressions, see about_Regular_Expressions.

Type:String[]
Position:0
Default value:None
Accept pipeline input:False
Accept wildcard characters:False

-Quiet

Indicates that the cmdlet returns a Boolean value (True or False), instead of a MatchInfo object. The value is True if the pattern is found; otherwise the value is False.

Type:SwitchParameter
Position:Named
Default value:False
Accept pipeline input:False
Accept wildcard characters:False

-Raw

Causes the cmdlet to output only the matching strings, rather than MatchInfo objects. This is the results in behavior that's the most similar to the Unix grep or Windows findstr.exe commands.

This parameter was introduced in PowerShell 7.

Type:SwitchParameter
Position:Named
Default value:False
Accept pipeline input:False
Accept wildcard characters:False

-SimpleMatch

Indicates that the cmdlet uses a simple match rather than a regular expression match. In a simple match, searches the input for the text in the Pattern parameter. It doesn't interpret the value of the Pattern parameter as a regular expression statement.

Also, when SimpleMatch is used, the Matches property of the MatchInfo object returned is empty.

Note

When this parameter is used with the AllMatches parameter, the AllMatches is ignored.

Type:SwitchParameter
Position:Named
Default value:False
Accept pipeline input:False
Accept wildcard characters:False

Inputs

PSObject

You can pipe any object that has a ToString method to .

Outputs

Microsoft.PowerShell.Commands.MatchInfo, System.Boolean, System.String

By default, the output is a set of MatchInfo objects with one for each match found. If you use the Quiet parameter, the output is a Boolean value indicating whether the pattern was found. If you use the Raw parameter, the output is a set of String objects that match the pattern.

Notes

is similar to grep in UNIX or findstr.exe in Windows.

The sls alias for the cmdlet was introduced in PowerShell 3.0.

Note

According to Approved Verbs for PowerShell Commands, the official alias prefix for cmdlets is , not . Therefore, the proper alias for should be , not . This is an exception to this rule.

To use , type the text that you want to find as the value of the Pattern parameter. To specify the text to be searched, use the following criteria:

  • Type the text in a quoted string, and then pipe it to .
  • Store a text string in a variable, and then specify the variable as the value of the InputObject parameter.
  • If the text is stored in files, use the Path parameter to specify the path to the files.

By default, interprets the value of the Pattern parameter as a regular expression. For more information, see about_Regular_Expressions. You can use the SimpleMatch parameter to override the regular expression matching. The SimpleMatch parameter finds instances of the value of the Pattern parameter in the input.

The default output of is a MatchInfo object, which includes detailed information about the matches. The information in the object is useful when you're searching for text in files, because MatchInfo objects have properties such as Filename and Line. When the input isn't from the file, the value of these parameters is InputStream.

If you don't need the information in the MatchInfo object, use the Quiet parameter. The Quiet parameter returns a Boolean value (True or False) to indicate whether it found a match, instead of a MatchInfo object.

When matching phrases, uses the current culture that is set for the system. To find the current culture, use the cmdlet.

To find the properties of a MatchInfo object, type the following command:

Related Links

Sours: https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/select-string

You will also be interested:

How to grep with PowerShell

Unix and Linux have had the incredibly powerful grep tool for decades but windows has always been lacking. PowerShell brings the functionality of grep with the Select-String cmdlet.

Use Select-String to Grep a Single File

To grep a simple text file is as easy as:

You can also use a wildcard:

Grep Recursively with Get-Childitem

Unlike grep, Select-String does not have the ability to search recursively, but you can pipe output to it from Get-ChildItem, like this:

Piping to Select-String

Just like grep, you can pipe to Select-String like this:

If you want to make it more like Unix/Linux, add an alias to the Select-String cmdlet:

Then you can simply pipe to Select-String like this:

Loop through results from Select-String

Here is an example that greps for a string and uses the results in a loop to determine if some action should be taken:

$pattern = "tachytelic" $files = Select-String -Path "d:\script\*.txt" -Pattern $pattern foreach ($file in $files) { $filename=$file.Filename $item = get-item $file.Path "File '{0}' matches the pattern '{1}'" -f $item.FullName, $pattern "It was last modified on {0}" -f $item.LastWriteTime $response = Read-Host -Prompt "Set the archive bit on this file?" If ($response -eq 'Y') { $item.attributes="Archive" } }

Which produces output like this:
Example output from Powershell providing grep functionality

grepping in Powershell seems to be incredibly fast, I have not conducted any testing against the performance of GNU Grep, but I don’t think you will be disappointed by the performance.

Filed Under: How ToTagged With: Powershell

Sours: https://www.tachytelic.net/2019/04/how-to-grep-using-powershell/


1443 1444 1445 1446 1447