We can use the comparison operator like with wildcard character to check if a property of object contains a specific string. Note: You can not use the comparison operator contains to check the contains string, because it’s designed to tell you if a collection of objects includes (‘contains’) a particular object.
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
.
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.
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.
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
.
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
PowerShell’s ‘If’ statement comes under the umbrella of flow control. Once you master the basic construction then you can increase its usefulness by appending, ‘Else’ and ‘ElseIf’ statements. One of my favourite alternative strategies is to use ‘Switch‘.
As with so many PowerShell constructions, the type of bracket signifies how to break the script into sections. It’s worth tattooing into our memory that (parenthesis brackets are for the first part, namely the condition), while {braces are for the block command}.
Summary: In PowerShell, ‘If’ executes statements conditional on the truth of the test expression.
Note 1: Trace the above construction, and separate the two components: if (test) and {what to do}.
Note 2: Avoid over-think; there is no ‘Then’ in a PowerShell ‘If’ statement. My advice is that instead of worrying about ‘If Then’, pay close attention to the two types of bracket. Furthermore, there is no endif in PowerShell as there is in VBScript.
Note 3: To double check your understanding, try amending, “Bigger than Zero” to a different text string, such as: “Less than nought”. Once you have done that, set $Number to -1 in the above Example 1a.
Note 4: You probably want to change the file referenced by $ChkFile. Indeed, the script cries out to be modified for a more constructive {outcome}.
Note 5: You could easily append an else statement to cater for a file not existing.Else {Write-Host 'File does not exist'}
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.
It’s rare that my first ‘If’ construction produces the desired results. The secret of success is to experiment with the If test, or alternatively start introducing one or more ‘ElseIf tests with their corresponding {outcome block}.
In this example I have introduced -Not into the logic:
Note 6: This script uses the Display Name property of the service. Remember in PowerShell ‘If Then’ does not exist. Observe it’s plain ‘If’.
Note 7: Observe in passing the If -Not construction; incidentally, -Not is sometimes abbreviated to an exclamation mark ! in PowerShell.
Note 8: This script cries out for an Else statement. We need to know if the named service has been installed.
Note 9: See more on -ErrorAction SilentlyContinue
Here is another real-life example of the ‘If statement’ in action. The idea is to ping 20 IP Addresses. The logic says If the StatusCode is 0, then display a label saying ‘ON NETWORK’.
Note 10: Once If statements get complicated it’s time to investigate PowerShell’s Switch parameter.
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.
PowerShell has a batch of help files. One of these files contains help about the ‘if’ statement. In the example below, $File references that file. $Content is set to the content of the file. The third line attempts to match a string to the contents of the file.
The above example is concerned with matching a string “The if Statement” to the contents of the built in help file.
This example deal with plain ‘Else’. This is a simple command, unlike ElseIf there is no second test construction, ‘Else’ just follows on to reflect what to do if the If statement is false.
The best way to see how ‘else’ operates is to amend line 3 thus:
($File -Match “The ifyyyy Statement”).
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!
The purpose of this script is to employ -Not logic to check for the Alerter service. One scenario is you are working with Windows 7 machines, and they no longer install this service.
Observe how -Not reverses the ‘If’ logic compared with Example 1.
Note 11: See more examples of PowerShell’s If -Not logic.
The purpose of this example is to check the status of a firewall on a Windows client machine such as Windows 8.1 or Windows 7.
This example has a real task; to check that we have the name of an actual file. Remember that the second (test statement) must be followed by a second {Block Script}.
Note 12: The advantage of ElseIf over plain Else, is that we can introduce a new test. In the above example we use ElseIf to check if the length of the file is less than 1. To activate the ‘ElseIf’ block, set $File to a non-existent file for example$File = Get-Help about_ifxx
Note 13: To trigger the final ‘Else’, try changing:$File = Get-Help about_if
to$File = Get-Help about_scope
If you have time, you could add more ‘ElseIf’ statements to cater for other eventualities. Alternatively, if the ElseIf construction is getting unwieldy, then try the superior switch command.
Import users from a spreadsheet. Just provide a list of the users with their fields in the top row, and save as .csv file. Then launch this FREE utility and match your fields with AD’s attributes, click and import the users.
Optionally, you can provide the name of the OU where the new accounts will be born. Download your FREE bulk import tool.
If you need more comprehensive application analysis software, Download a free trial of SAM (Server & Application Monitor)
If you would another account of PowerShell’s If statement, then have a look at the built-in help file
This is Microsoft’s explanation:
Windows PowerShell evaluates the <test1> conditional expression as either true or false. Should the result be true, PowerShell obeys whatever is inside the {curly brackets}, whereupon PowerShell exits the If statement.
In the event of the first test being false PowerShell works its way through the ElseIf statements.
Incidentally, the ‘Vehicle’ for our tests reveals a whole family of ‘about_zyx…’ files. My point is there is no command: ‘Get-Help if’, however, there is a help file called, ‘about_if’. Furthermore, if you look in the PowerShell directory then you will see ‘About’ files to assist with commands such as ‘If’ and ‘ElseIf’. You can list these ‘About’ files with the command:
When it comes to filtering output, one of the oldest and best statements is the ‘If’ clause. As usual, the secret of understanding the syntax is to pay close attention to the style of bracket. If (parenthesis for the test) and {braces for the action}. Once you have mastered the basic ‘If’ statement, then extend your capabilities by researching ‘Else’ and ‘ElseIf’.
If you like this page then please share it with your friends
• PowerShell Home • PowerShell If Statement • PowerShell ElseIf • Free Permissions Analyzer
• Conditional Operators • PowerShell -Match • PowerShell -Like • PowerShell -Contains
• PowerShell Comparison Operators • PowerShell Syntax • Where Filter • PowerShell Else
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.