Powershell Check If File Contains String

Wrote this small part of code to check if file exist and contains string pattern. How can I replace every occurrence of a String in a file with PowerShell? How to unzip a file in Powershell? Powershell - Does file exist on users machine output specific file. Hot Network Questions. Long story short, I am putting together a quick script to check for DFS Replication backlogging. This all works beautifully until I encounter a Replication Group Name with a space in it. I am currently taking user input for a variable. If that input contains a space, I want to encapsulate the string in double quotes.

  1. Powershell Check If File Path Contains String
  2. Powershell Check If File Contains String Recursive
  3. Powershell Where String Contains
  4. Powershell Check List Contains
  5. Powershell Check If File Contains String Java

At some point during your PowerShelling career you will need to test if “something” is found (or not found) within a certain object. I find that I am usually faced with this situation when I am testing if a string “contains” a value or not.

At this point, I am always confused as to which comparison operator to use. From a logical language perspective I always feel like -contains is the way to go, but then I remember that might not be the correct choice.

To put this issue to bed once and for all (at least for myself), here is a summary of when to use -like and when to use -contains.

PowerShell -like Comparison Operator

Here is how Microsoft TechNet describes the use for -like:

-Like
Description:
Match using the wildcard character (*).

Example:
PS C:> “Windows PowerShell” -like “*shell”
True

PS C:> “Windows PowerShell”, “Server” -like “*shell”
Windows PowerShell

Here is my version:

-like is used to compare or find if a string exists within another string. -like allows you to use the wildcard character (*) so you can search anywhere within the string.

So back to my initial requirement of determining if a string contains a particular value or not, we would use the -like operator. See some examples below:

In example 1, the result is false because there are no wildcards, therefore its checking to see if the string matches exactly.

In example 2 we added the wildcard (*) at the end of the search term. This essentially means check if xyz exists at the beginning of the string and then ignore the rest. In this case it doesn’t, hence the result is false.

In example 3 we are doing the same as example 2 but searching for abc* and therefore returns true because abc is found at the beginning of the string. The rest is then ignored due to the wildcard.

Example 4 is essentially a reverse of example 3. We are searching for xyz at the end of the string and don’t care about anything in front of it (hence the wildcard in the front of the search term).

Example 5 shows searching for something in the middle of the string by using wildcards on either side of the search term.

PowerShell -contains Comparison Operator

Here is how Microsoft TechNet describes the use for -contains:

Description:
Containment operator. Tells whether a collection of reference values includes a single test value. Always returns a Boolean value. Returns TRUE only when the test value exactly matches at least one of the reference values.

When the test value is a collection, the Contains operator uses reference equality. It returns TRUE only when one of the reference values is the same instance of the test value object.

Syntax:
-Contains

Examples:
PS C:> “abc”, “def” -Contains “def”
True

PS C:> “Windows”, “PowerShell” -Contains “Shell”
False #Not an exact match

# Does the list of computers in $domainServers
# include $thisComputer?
# ——————————————
PS C:> $domainServers -Contains $thisComputer
True

PS C:> “abc”, “def”, “ghi” -Contains “abc”, “def”
False

PS C:> $a = “abc”, “def”
PS C:> “abc”, “def”, “ghi” -Contains $a
False
PS C:> $a, “ghi” -Contains $a
True

Now here is my version….

The -contains comparison operator is used to determine if a collection of objects (e.g. an array) contains a particular object or not. The evaluation is completed against the entire object and not any single object property. In other words, all of the object’s properties are taken into consideration.

That might be a little confusing, but looking at some examples might clear things ups somewhat:

The first example is an easy one, an array with each object being a string and therefore makes the comparison really easy. The example above is searching for the array object (array element) of xyz. As there is an array element that matches xyz it will return true.

Now you would expect that the example above would return true, because every Windows system has a W32Time service, but it doesn’t… why? Well because we are attempting to find an object based on a single property, name. The -contains operator doesn’t work like this however. It compares every single property of the object and if all of them are the same then it returns True, else it will return false.

In the example above, we are essentially comparing a string object with a System.ServiceProcess.ServiceController object, which isn’t going to work.

In order to find a service with the name property we would need to do:

Although this works, it might not be the best result because W32Time might be the value of a property within another service and hence you might get some false positives.

To remove the risk of false positives, I would personally do something like:

Enumerating all services in the collection and determining if each of their name properties equal the search term is a very accurate way to determine if the particular service exists or not and will eliminate all false positives. More code, but a better solution.

Not Searches?

As a quick side-note, what happens if you want determine if something does not contain a particular search term?

Well in that case just use -NotLike or -NotContains in the same fashion and in the same situations as you would use -like and -contains.

More Info on Comparison Operators

If you want to learn more about all the comparison operators, then check out the TechNet Comparison Operators page.

Well I hope that helps make things a little clearer on when to use -Like and when to use -Contains.

Let me know your thoughts below…

Thanks
Luca

TagsAutomation, PowerShell, Scripting

Windows PowerShell -Contains

When it comes filtering, or finding data we are spoilt for choice with -Match, -Like and -Contains. While there is overlap, each conditional operator has a distinctive role in PowerShell scripting.

-Contains is best for seeking an exact value. If I want a command to return either True or False, I start with -Contains, whereas, if I want a list of results then I try -Match or -Like.

Topics for PowerShell’s -Contains Conditional Operator

Powershell Check If File Contains String

Example 1a: PowerShell -Contains

PowerShell uses singular nouns; thus “contains” is a verb, and not a plural noun. A feature of -Contains is that usually returns “True” or “False. If you are looking for a command to return a list of values, then employ -Match or -Like.

Example 1b: PowerShell’s -Contains is Very Strict

-Contains can be frustrating because it’s so picky. After a while you realize that this just a design feature, if you don’t like it, try -Match.

Note 1: -Contains interprets “Flats” and “Flat” as different, thus returns False; it does not matter that Flat is a subset of Flats.

Powershell Check If File Path Contains String

Challenge: Substitute -Match for -Contains.

Guy Recommends: Free WMI Monitor for PowerShell (FREE TOOL)

Windows Management Instrumentation (WMI) is one of the hidden treasures of Microsoft’s operating systems. Fortunately, SolarWinds have created a Free WMI Monitor for PowerShell so that you can discover these gems of performance information, and thus improve your PowerShell scripts.

Take the guesswork out of which WMI counters to use when scripting the operating system, Active Directory, or Exchange Server. Give this WMI monitor a try – it’s free.

Example 2: Seeking a Value in a Collection

-Contains would be my choice of conditional operators for situations where I wanted to test for one particular item in a collection, array or a hashtable.

Note 2: If you coded: $Collection -Contains “Paula Harris”
The result would be: True. You need an exact match of the full item.

Note 3: $Collection -Contains “Paula*” does not help. Wildcards are next to useless with -Contains. Better: try -Match Paula, or -Like Paula*

Example 3: PowerShell -Contains Spreadsheet

Let us assume we wish to search in a file called links.csv. Furthermore, we can use Import-Csv to read the data so that we can test values with -Contains.

Preparation
My spreadsheet is called links.csv
I stored the file in D:PowerShell
The column name is “Custom channel”
See screenshot to the right.

Guy Recommends: Network Performance Monitor (FREE TRIAL)

SolarWinds Network Performance Monitor (NPM) will help you discover what’s happening on your network. This utility will also guide you through troubleshooting; the dashboard will indicate whether the root cause is a broken link, faulty equipment or resource overload.

What I like best is the way NPM suggests solutions to network problems. Its also has the ability to monitor the health of individual VMware virtual machines. If you are interested in troubleshooting, and creating network maps, then I recommend that you try NPM on a 30-day free trial.

Example 4: PowerShell -CContains

Powershell Check If File Contains String Recursive

As with PowerShell’s other conditional operators, you can force them to be case sensitivity by preceding the command with a ‘C’; CContains is not a typo!

Note 4: The point is that in the spreadsheet the value is clearly ‘LinkTop’, when we force case-sensitivity with CContains, this is not the same as ‘linktop’, hence a False result.

Example 5: PowerShell -NotContains

The negative -NotContains is not as useful as -NotMatch. However, from what we have already learned the syntax is predictable.

Note 5: Remember that with -Contains, and by extension -NotContains, the match has to be exact. There is no ‘Custom channel’ with the name of precisely ‘link’.

Guy Recommends: SolarWinds Engineer’s Toolset (FREE TRIAL)

This Engineer’s Toolset provides a comprehensive console of 50 utilities for troubleshooting computer problems. Guy says it helps me monitor what’s occurring on the network, and each tool teaches me more about how the underlying system operates.

There are so many good gadgets; it’s like having free rein of a sweetshop. Thankfully the utilities are displayed logically: monitoring, network discovery, diagnostic, and Cisco tools. Try the SolarWinds Engineer’s Toolset on a 14-day free trial now!

About_Operators

Here is the List of the Types of PowerShell’s Operators

  • Arithmetic (+ * – /)
  • Assignment (= also -= +=)
  • Comparison ( -Match and -Like; also: -eq -gt)
  • Logical ( -And -Not)
  • Redirectional ( > )
  • Split and Join ( -split)
  • Type (-Is -Isnot)
  • Unary ($i++)

Summary of PowerShell’s -Contains Conditional Operator

When you seek an exact value, then -Contains would be my first choice of conditional operator. -Match or -Like are better suited to scenarios where you only need a partial match, or you need a list of items.

See more Windows PowerShell flow control examples

• PowerShell Home • PowerShell If Statement • PowerShell ElseIf • Free Permissions Analyzer

Powershell Where String Contains

• Conditional Operators • PowerShell -Match • PowerShell -Like • PowerShell -Contains

Powershell Check List Contains

• PowerShell Comparison Operators • PowerShell Syntax • Where Filter • PowerShell Else

Powershell Check If File Contains String Java

Please email me if you have a better example script. Also please report any factual mistakes, grammatical errors or broken links, I will be happy to correct the fault.