Arrays allow you to store multiple values in one variable. This way you can easily loop through each value and process it in your script. But sometimes you need to check if the PowerShell array contains a specific value.
To check if a value exists in an array, we can use the -Contains operator in PowerShell. This will return return true if the value exists. But there are other options as well.
The recommended way to check if an array contains a specific value is by using the -contains operator or the .Contains() method in PowerShell. Even though both look similar, there are some important differences between the two.
First, let’s take a quick look at how to use the -contains operator. To simply check if a string is in an array you can do the following:
$array = @('apple', 'banana', 'cherry')
if ($array -contains 'banana') {
Write-Host "Array contains banana"
}else{
Write-Host "Banana not found in the array"
}
The method above will simply check if the string exists in the array. The comparison is case insensitive, and the operator will stop when the results are found. So when an item, a fruit in the example above, is listed multiple times in the array, then it will still just return True or False.
So there are a couple of other options when it comes to checking if a value is listed in an array. Besides the .Contains() method, we can also use:
-in operator – checks if a value is in an array, just another way of writing it. -ccontains operator – case-sensitive comparison -eq – Can also check if an array contains a specific value Where-Object – Allows you to do more complex comparisons
So I want to first explain the difference between the contains operator and the contains method. Because they look really similar, but there is more to it.
The Contains method, written .contains(), is a method from the underlying .NET framework, whereas the operator is specific to PowerShell. Now the .NET method is faster, so when you need to look up a value in a large array, then there is a real benefit there.
Another important difference between the two is that the contains method is case-sensitive by default, whereas the operator is not:
$array = @('apple', 'banana', 'cherry', 'banana')
$array -contains 'Banana' # Returns true
$array.Contains('Banana') # Returns false
As mentioned, the contains operator is case-in-sensitive, which is often perfectly fine. But when you can also do an exact case value match, by using the -ccontains operator (note the double c).
$array = @('apple', 'banana', 'cherry', 'banana')
# Case sensitive comparison
$array -ccontains 'Banana' # Returns false
Instead of checking if an array contains a specific value, we can also check if an array does not contains a specified value. To do this, we can use the -notcontains operator. The operator will return True if the value is not listed in the array.
For example, we have a list of users who have completed a security training, and we want to verify if a particular user has not completed it yet. In this case, -notcontains is a more logical option to use:
# List of users
$completedTraining = @('John', 'Alice', 'Robert', 'Sarah')
# Check if the user has not completed the training
if ($completedTraining -notcontains 'Jane'){
Write-Host "Jane didn't completed the training"
}
The -in operator is the same as the contains operator, only reversed. It also returns true when the value is in the array, the only difference is that you place the array on the right of the operator, instead of the left.
You should use the -in operator when it’s more intuitive and concise for the situation. For example, if we want to check if a user is a member of an Admin group, then it makes more sense to check if “Jane” is in the admin group, than to check if the admin group contains “Jane”:
# List of admin users
$adminUsers = @('John', 'Alice', 'Robert')
# Using the -in operator
if ('Alice' -in $adminUsers) {
Write-Output "Alice is an admin."
}
The key here is to make your code easier to read and understand. You can also use the -notin operator, which checks if a value is not in the array.
You might not expect it, but we can also use the -eq operator to check if an array contains a specific value in PowerShell. The big difference with the -contains operator, however, the equal operator does not return true or false, but it returns the value.
And, even more importantly, it does not stop searching for the value when the value is found. This means that we can also count or check if a value is listed multiple times in an array:
$array = @('apple', 'banana', 'cherry', 'banana')
$result = $array -eq "banana"
if ($result) {
Write-Host "Banana is listed $($result.Length) time(s) in the array"
}
Result
Banana is listed 2 time(s) in the array
The last option that I want to show you is the Where-Object method to check if an array contains a specific value. This method is mainly used when you have an array of objects or need to do other complex comparisons.
For example, we have an array with user objects, and want to check if the array contains a specific user:
$users = @(
[PSCustomObject]@{ Name = 'John'; Age = 30 },
[PSCustomObject]@{ Name = 'Jane'; Age = 25 },
[PSCustomObject]@{ Name = 'Alice'; Age = 28 }
)
$result = $users | Where-Object { $_.Name -contains 'Jane'}
The most common way to check if an array contains a specific value is by using the -contains operator. Keep in mind though, that this is case-in-sensitive, whereas the .contains() method is case-sensitive.
Try to use the appropriate operator for the situation, this will make your code easier to read and understand.
In PowerShell 5, there are several different types of arrays that you can work with. Here are the main types
Numeric arrays: Numeric arrays in PowerShell are created using integer indices. The index of the first element is 0, and subsequent elements have indices increasing by 1. Numeric arrays can store any type of data, including strings, numbers, and objects
$numericArray = @(1, 2, 3, 4, 5)
Associative arrays (also known as hash tables): Associative arrays use key-value pairs to store data. Each element in the array is accessed using a unique key instead of an index. Keys can be of any data type, and values can be any PowerShell object
$associativeArray = @{
"Name" = "John Doe"
"Age" = 30
"City" = "New York"
}
Multidimensional arrays: PowerShell supports multidimensional arrays, which are arrays with more than one dimension. You can create arrays with two or more dimensions to store data in a tabular or matrix-like structure
$multiDimArray = @(
@(1, 2, 3),
@(4, 5, 6),
@(7, 8, 9)
)
Jagged arrays: Jagged arrays are arrays of arrays, where each subarray can have a different length. This allows you to create arrays with varying lengths within a single array
$jaggedArray = @(
@(1, 2, 3),
@(4, 5),
@(6, 7, 8, 9)
)
Numerical Array:
- Indices: Numerical arrays use integer indices to access and identify elements. The indices typically start from 0 and increment by 1 for each subsequent element.
- Element Type: Numerical arrays are often used to store numeric values, such as integers or floating-point numbers.
$numericalArray = @(1, 2, 3, 4, 5)
Regular Array (Indexed Array):
- Indices: Regular arrays also use integer indices to access and identify elements, similar to numerical arrays.
- Element Type: Regular arrays can store elements of any data type, including strings, numbers, objects, or even a mixture of different data types.
- Example:
$regularArray = @("Apple", "Banana", "Orange", "Grape")
The key difference between the two lies in the intended usage and the types of values typically stored. Numerical arrays are often used when the elements have a numeric nature, while regular arrays offer flexibility and can store various types of data.
In PowerShell, the term "numerical array" is not an official designation or a specific data type; rather, it is a descriptive term used to refer to arrays that predominantly store numeric values. Regular arrays, on the other hand, can encompass arrays that hold any type of data.
Both numerical arrays and regular arrays use indices to access elements, but the distinction lies in the expected data types and the common use cases associated with each.
Complex Expressions: When you want to embed a complex expression within a string, you can use $( )
to ensure that the expression is evaluated correctly.
$num = 5
Write-Host "The result is $($num * 2)"
The result is 10
Variable Names with Special Characters: If your variable name contains special characters, spaces, or includes properties or methods, using $( )
helps ensure that the entire variable reference is evaluated correctly.
$person = [PSCustomObject]@{
Name = "John Doe"
Age = 30
}
Write-Host "Person's name is $($person.Name)"
Person's name is John Doe
Nested Variable Expansion: If you want to expand multiple variables within a string, you can use $( )
to nest variable references and ensure proper evaluation.
$name = "John"
$greeting = "Hello, $($name)!"
Write-Host $greeting
Hello, John!
In summary, you can use $( )
in PowerShell to enclose complex expressions, reference variables with special characters, or nest multiple variable expansions within a string. In simpler cases, where you are directly accessing the value of a variable without any additional complexity, you can omit $( )
.