What can you do with the Select-String cmdlet? Well, one thing you can do is determine whether or not a specific string value exists in a text file. For example, suppose the file C:\Scripts\Test.txt is a log file that contains the following information:
1 2 3 4 5 |
Operation succeeded, 5/1/2014 Operation succeeded, 5/2/2014 Operation failed, 5/3/2014 Operation succeeded, 5/4/2014 Operation succeeded, 5/5/2014 |
You’d like to be able to quickly scan the contents of the file and see whether the word Failed appears anywhere. If it does, that means one of your operations failed; if it doesn’t, that means all of your operations succeeded. (And yes, seeing as how we’re talking about failed operations we do hope you’re not a surgeon.) Here’s how you can do that:
1 |
Get-Content c:\scripts\test.txt | Select-String "Failed" -quiet |
What we’re doing here is using the Get-Content cmdlet to retrieve the contents of the file C:\Scripts\Test.txt. We’re then piping those contents to the Select-String cmdlet and asking Select-String to search for the target string. By adding the -quiet parameter we get back a True if the string is found and nothing if the string is not found. If we leave off the -quiet parameter then Windows PowerShell returns each line in the text file that includes the target string:
1 |
Operation failed, 5/3/2014 |
Another Select-String parameter that you might find useful is -casesensitive, which performs a case-sensitive search of, in this case, the text file. This particular command will return nothing, meaning that the target string Failed could not be found:
1 |
Get-Content c:\scripts\test.txt | Select-String "Failed" -quiet -casesensitive |
Why couldn’t Failed be found in the text file? That’s easy: based on letter case, there’s no such string in the file. The file contains the string failed with a lowercase f, while the target search string is Failed with an uppercase F. If you change the target string to failed (or remove the -casesensitive parameter) the command returns True.