
In this article, we will explore everything you need to know about PowerShell comparison operators, including their types, syntax, and examples. We’ll also look into their benefits and best practices for using them effectively.
I have another script that outputs data into a csv file every 4 hours and creates the files as vdsinfo_$(Get-Date -Format "yyMMdd_hh-mm-ss").csv.
I want to be able to compare the original file created and also the last two files created against each other to see if there has changes within the file.
At the moment, this is what I have for the script but it isn’t quite there yet and would really appreciate some help to get this producing an output written to a Changes.csv file.
I want to compare files that file names are always changing so the script needs to be using variables where possible and only way I can see this working is by the get-date addhours-4.
$File = 'E:\TEMP\Changes.csv'
# Get File item
$file1 = Get-ChildItem -Path E:\TEMP\reports\vdsinfo_original.csv
# Get the specific date
$date1 = (Get-Date).AddHours(-8)
# Compare file modified date with specific date
$file2 = $file1.LastWriteTime -gt $date1
Compare-Object -ReferenceObject $file1 -DifferenceObject $file2 -CaseSensitive | Format-table InputObject, SideIndicator -Autosize | out-file $file -Width 200
Else { Write-Host "File missing " -ForegroundColor White -BackgroundColor Red
}Any help would really help me, thanks in advance
With this current script it only does comparison against two files and I’d like to compare against the original and the last two files within the folder location.
Introduction to PowerShell Comparison Operators
Before we dive into the details, let’s define what PowerShell comparison operators are and why they are important. Comparison operators are symbols or words used to compare two values and return a Boolean (true or false) result. PowerShell uses comparison operators to evaluate expressions, test conditions, and perform logical operations. In PowerShell, comparison operators are used to compare strings, numbers, and other objects, and they are a key component of conditional statements, loops, and filtering operations.
PowerShell’s comparison operators are symbols or words used to compare two values and return a Boolean (true or false) result. There are a variety of comparison operators available in PowerShell, including equals, not equal, greater than, greater than or equal, less than, and less than or equal. These operators are used to compare strings, numbers, dates, boolean, and other objects, and they are a key component of conditional statements, loops, and filtering operations.
List of Comparison Operators in PowerShell
Here is a list of commonly used comparison operators in PowerShell:
| Operator | Description |
|---|---|
| -eq | Equal to |
| -ne | Not equal to |
| -gt | Greater than |
| -ge | Greater than or equal to |
| -lt | Less than |
| -le | Less than or equal to |
| -like | Wildcard comparison |
| -notlike | Negative wildcard comparison |
| -match | Regular expression comparison = |
| -notmatch | Negative regular expression comparison |
| -contains | Containment operator |
| -notcontains | Negative containment operator |
| -in | Checks if a value is in a set of values |
| -notin | Checks if a value is not in a set of values |
| -is | Returns True if the object on its left-hand side is of the type specified on its right-hand side. |
| -isnot | Returns True if the object on its left-hand side is not of the type specified on its right-hand side. |
| -replace | replaces strings matching a regex pattern |
Please note that PowerShell comparison operators are case-insensitive by default. If you want to perform a case-sensitive comparison, you can use the case-sensitive versions of these operators, which are the same but with a ‘c’ prefix, like -ceq, -cne, -clike, -cnotlike, -cmatch, and -cnotmatch. Similarly, there are case-insensitive versions of the operators with an ‘i’ prefix, like -ieq, -ine, -ilike, -inotlike, -imatch, and -inotmatch.
Real-world examples of using PowerShell comparison operators
In real-world scenarios, PowerShell comparison operators are used extensively to perform various tasks. Some examples include:
- Checking if a file exists before performing an operation.
- Validating user input against predefined values or patterns.
- Filtering and manipulating data based on specific criteria.
- Comparing timestamps to determine the age of files or folders.
- Testing and validating conditions in control flow statements, such as loops and conditional statements.
These examples highlight the versatility and importance of PowerShell comparison operators in everyday scripting tasks.
Syntax of Comparison Operators
In this example, we are using the equality operator (-eq) to compare $value1 and $value2. If the values are equal, the expression will evaluate to $true; otherwise, it will evaluate to $false.
Do you need to compare two arrays to find matches in PowerShell? In this article, we’ll explore different methods to compare two arrays for matches in PowerShell with complete examples.
To compare two arrays for matches in PowerShell, you can use the Compare-Object cmdlet with the -ReferenceObject and -DifferenceObject parameters to identify similarities. Alternatively, loop through one array and use the -contains operator to check if each item exists in the second array. For a more concise approach, leverage LINQ’s Intersect method to find common elements directly.
Now, let us check out how to compare two arrays for matches in PowerShell.
Method 1: Using Loops
The most basic method to compare two arrays is by using loops to iterate through each element and check for matches in PowerShell.
$array1 = @('apple', 'banana', 'cherry')
$array2 = @('banana', 'kiwi', 'apple')
foreach ($item1 in $array1) { foreach ($item2 in $array2) { if ($item1 -eq $item2) { Write-Output "Match found: $item1" } }
}In this example, we have two arrays $array1 and $array2, and we use nested foreach loops to iterate through each element. If an element from $array1 matches an element from $array2, we output the match.
You can see the output in the screenshot below after I executed the VS code.

Method 2: Using -contains Operator
A more efficient way to find matches is to use the -contains operator, which checks if a single value is present in an array in PowerShell.
$array1 = @('apple', 'banana', 'cherry')
$array2 = @('banana', 'kiwi', 'apple')
foreach ($elem in $array1) { if ($array2 -contains $elem) { Write-Output "Match found: $elem" }
}This method is more straightforward and faster than using nested loops, as it eliminates the need for the inner loop.
Method 3: Using Compare-Object Cmdlet
PowerShell provides a cmdlet called Compare-Object that compares two sets of objects. It’s a powerful tool that can show differences as well as similarities between arrays in PowerShell.
$array1 = @('apple', 'banana', 'cherry')
$array2 = @('banana', 'kiwi', 'apple')
$comparison = Compare-Object -ReferenceObject $array1 -DifferenceObject $array2 -IncludeEqual
foreach ($result in $comparison) { if ($result.SideIndicator -eq '==') { Write-Output "Match found: $($result.InputObject)" }
}The Compare-Object cmdlet uses -ReferenceObject and -DifferenceObject parameters to specify the arrays to compare. The SideIndicator property tells us whether the object is present in both arrays (==), only in the reference array (<=), or only in the difference array (=>).
You can see this in the screenshot below:

Method 4: Using LINQ
For those who are familiar with .NET, PowerShell can leverage the LINQ (Language Integrated Query) to compare arrays.
$array1 = @('apple', 'banana', 'cherry')
$array2 = @('banana', 'kiwi', 'apple')
$matches = [System.Linq.Enumerable]::Intersect($array1, $array2)
foreach ($match in $matches) { Write-Output "Match found: $match"
}Here, we use the Intersect method from the System.Linq.Enumerable class to find common elements between $array1 and $array2.
Conclusion
Comparing arrays for matches in PowerShell can be done using different methods. You can use the simple loops and the -contains operator to understand the basics of array comparison in PowerShell. As you become more comfortable with PowerShell, you can use more advanced methods like Compare-Object or LINQ to perform the same task more efficiently.
In this PowerShell tutorial, I have explained how to compare two arrays for matches in PowerShell using various methods and examples.
You may also like:
Do you need to compare two arrays in PowerShell? In this PowerShell tutorial, I will explain everything about Array comparisons in PowerShell using various methods with examples. We will explore how to compare arrays in PowerShell.
To compare arrays in PowerShell, the Compare-Object cmdlet is commonly used, which compares two sets of objects by serving one as the reference set and the other as the difference set to identify items that are equal or unique to each array. For a more manual approach, the -contains operator can be used to check if an array contains a specific element by iterating through each item.
Compare Arrays in PowerShell
An array is a data structure that holds a collection of items, which can be of any data type. You can create an array in PowerShell by assigning multiple values to a variable, separated by commas:
$array1 = 1, 2, 3, 4, 5
$array2 = 3, 4, 5, 6, 7Now, let’s look at different methods to compare these arrays in PowerShell.
Method 1: Compare-Object Cmdlet
The most straightforward way to compare arrays in PowerShell is by using the Compare-Object cmdlet. This cmdlet takes two arrays as input and returns the differences between them.
Compare-Object -ReferenceObject $array1 -DifferenceObject $array2When you run this command, PowerShell will display items that are unique to each array. By default, the output will include two symbols:
<=indicates the item is unique to the reference object ($array1in this case).=>indicates the item is unique to the difference object ($array2in this case).
Example:
$array1 = 1, 2, 3, 4, 5
$array2 = 3, 4, 5, 6, 7
Compare-Object -ReferenceObject $array1 -DifferenceObject $array2This will output, you can see, after I executed the PowerShell script using VS code. Check the screenshot below:

InputObject SideIndicator
----------- ------------- 6 => 7 => 1 <= 2 <=Method 2: Using Loops for Comparison
Another way to compare arrays in PowerShell is by using loops. You can iterate through each item in one array and check if it exists in the other array.
Example:
$array1 = 1, 2, 3, 4, 5
$array2 = 3, 4, 5, 6, 7
foreach ($item in $array1) { if ($array2 -notcontains $item) { Write-Host "$item is not in array2" }
}
foreach ($item in $array2) { if ($array1 -notcontains $item) { Write-Host "$item is not in array1" }
}This script will output:
1 is not in array2
2 is not in array2
6 is not in array1
7 is not in array1Check out the screenshot below for your reference, I have expected the complete script using VS code.

Method 3: Using Custom Functions
Example:
function Compare-Array { param( [array]$array1, [array]$array2 ) $result = @() foreach ($item in $array1) { if ($array2 -notcontains $item) { $result += "$item is unique to array1" } } foreach ($item in $array2) { if ($array1 -notcontains $item) { $result += "$item is unique to array2" } } return $result
}
$array1 = 1, 2, 3, 4, 5
$array2 = 3, 4, 5, 6, 7
Compare-Array -array1 $array1 -array2 $array2Running this function will give you a similar output to the loop example but in a cleaner and more reusable format.
Method 4: Using LINQ in PowerShell
Example:
$array1 = 1, 2, 3, 4, 5
$array2 = 3, 4, 5, 6, 7
$onlyInArray1 = [System.Linq.Enumerable]::Except([int[]]$array1, [int[]]$array2)
$onlyInArray2 = [System.Linq.Enumerable]::Except([int[]]$array2, [int[]]$array1)
$onlyInArray1
$onlyInArray2This will output the items that are unique to each array using LINQ’s Except method.
Conclusion
Comparing arrays in PowerShell can be accomplished using various methods, from the simple Compare-Object cmdlet to more complex custom functions like loops or even LINQ.
In this PowerShell tutorial, I have explained how to compare arrays in PowerShell using different methods and examples.
You may also like:
Tips for Using PowerShell Comparison Operators
To get the most out of PowerShell comparison operators, keep these tips in mind:
- Use the appropriate operator: Choose the comparison operator that best fits the type of values you are comparing (e.g., strings vs. numbers).
- Be consistent: Use the same type of quotes (single or double) consistently in your scripts to avoid errors.
- Test your scripts: Always test your scripts thoroughly to ensure that your comparisons are working as expected.
- Use parentheses: When you use multiple comparison operators in a single statement, use parentheses to ensure that the comparisons are evaluated in the correct order.
- Consider case-sensitivity: By default, string comparison in PowerShell is case-insensitive. If you need to perform a case-sensitive comparison, use the appropriate case-sensitive operators or techniques.
- Use variables and constants instead of hard-coding values in your scripts.
- Use logical operators such as -and and -or to combine multiple conditions.
- Use the -not operator to negate a condition.
- Use the -contains and -notcontains operators for array and collection searches.
- Use the -match and -notmatch operators for regular expression searches.
- Use the -like and -notlike operators for string wildcards.
- Last but not least: Use comments for clarity: When writing scripts involving comparisons, it is a good practice to use comments to explain the purpose and logic of the comparisons. This helps other readers (including yourself) understand the code more easily.
Benefits of Using PowerShell Comparison Operators
Using PowerShell comparison operators offers a number of benefits, including:
- Increased efficiency: Comparison operators enable you to quickly and easily compare values and make decisions based on those comparisons, which can save time and reduce errors in your scripts.
- Greater flexibility: With a variety of comparison operators available, you can tailor your scripts to your specific needs and easily modify them as your requirements change.
- Improved accuracy: Comparison operators ensure that your scripts are making accurate comparisons based on the specific criteria you specify.
Overall, using PowerShell comparison operators can help you write more efficient, flexible, and accurate scripts.
Types of Comparison Operators
PowerShell includes several types of comparison operators, each with its own syntax and purpose. Here is a brief overview of the different types of comparison operators:
Equality Operators
-eq: Equal-ne: Not Equal-gt: Greater Than-ge: Greater Than or Equal To-lt: Less Than-le: Less Than or Equal To
Example: Equality Operators
$value1 = 10
$value2 = 20
if ($value1 -eq $value2) { Write-Host "The values are equal."
} else { Write-Host "The values are not equal."
}In this example, we are comparing $value1 and $value2 using the equality operator (-eq). Since the values are not equal, the expression will evaluate to $false, and the output will be “The values are not equal.”
Example: Using the Greater Than Operator
$age = 25
if ($age -gt 18) { Write-Output "You are old enough to vote."
} else { Write-Output "You are not old enough to vote."
}This script uses the PowerShell greater than operator to compare the value of the $age variable to the integer 18. If the value of $age is greater than 18, the script outputs, “You are old enough to vote.”. If the value of $age is less than or equal to 18, the script outputs: “You are not old enough to vote.”.
Less than or equal, greater than or equal, not equal operators
To better understand how PowerShell comparison operators work in practice, here are some examples of how they can be used in scripts:
$number = 10
if ($number -le 20) { Write-Host "The number is less than or equal to 20."
}
if ($number -ge 5) { Write-Host "The number is greater than or equal to 5."
}
if ($number -ne 7) { Write-Host "The number is not equal to 7."
}These examples demonstrate the practical usage of PowerShell comparison operators and showcase their versatility in different scenarios.
Using the Equals Operator for String Comparison
The -eq operator checks whether two strings are equal. For example,
$name = "John"
if ($name -eq "John") { Write-Output "Hello, John!"
} else { Write-Output "Who are you?"
}This script uses the PowerShell equals operator to compare the value of the $name variable to the string “John”. If the two values are equal, the script outputs “Hello, John!”. If they are not equal, the script outputs, “Who are you?”.
Case-Sensitive Compare Operators
The PowerShell case-sensitive compare operators (-ceq, -cne, -cgt, -cge, -clt, and -cle) are used to compare strings in a case-sensitive manner. For example:
PS C:\> "John" -ceq "john" False
Pattern Matching Operators
-like: Like-notlike: Not Like-match: Match-notmatch: Not Match
Example: Matching Operators
$name = "John Doe"
if ($name -like "John*") { Write-Host "The name starts with 'John'."
} else { Write-Host "The name does not start with 'John'."
}In this example, we are using the matching operator (-like) to check if the $name variable starts with “John”. Since the name does start with “John”, the expression will evaluate to $true, and the output will be “The name starts with ‘John’.”
Here is another example to check if $Filename ends with .txt using the -like operator.
$Filename = "Document.txt" $Filename -like "*.txt" # This will return True
Similarly, you use the -match operator in PowerShell to find a match for a pattern in a string using regular expressions. Here’s a simple example:
# Define a string $string = "Hello123" # Use -match to find a pattern $result = $string -match "\d" # \d matches any digit # Output result $result # Returns True as the digit is found
In this script, the -match operator looks for the pattern “\d” (which represents any digit in regular expressions) in the string “Hello123”. Since there are digits in “Hello123”, $result is True.
Containment Operators
-contains: Contains-notcontains: Not Contains-in: In-notin: Not In
Example: Containment Operators
$numbers = 1, 2, 3, 4, 5
if ($numbers -contains 3) { Write-Host "The collection contains the number 3."
} else { Write-Host "The collection does not contain the number 3."
}In this example, we are using the containment operator (-contains) to check if the $numbers collection contains the number 3. Since the collection does contain the number 3, the expression will be evaluated $true, and the output will be “The collection contains the number 3.”
Let’s take a look at how the “In” operator can be used:
$Names = "John", "Jane", "Jack" "Jane" -in $Names # This will return True "Jill" -notin $Names # This will return True

Type Operators
-is: Is-isnot: Is Not
Example: Type Operators
$value1 = "Hello"
$value2 = 10
if ($value1 -is [string] -and $value2 -is [int]) { Write-Host "Both values are of the correct type."
} else { Write-Host "One or both values are not of the correct type."
}Replacement Operators
$name = "John Doe" $newName = $name -replace "Doe", "Smith" Write-Host "The new name is: $newName"
In this example, we are using the replacement operator (-replace) to replace the specified value last name “Doe” with “Smith”. The output will be “The new name is: John Smith”.

Date comparison Operators in PowerShell
PowerShell provides date comparison operators that allow you to compare dates. These operators include -eq (equals), -ne (not equals), -gt (greater than), -lt (less than), -ge (greater than or equal to), and -le (less than or equal to). These operators are useful when you are working with dates and need to perform comparisons.
$date = Get-date
if ($date -ge (Get-Date "2022-01-01")) { Write-Host "The date is greater than or equal to 2022-01-01."
} else { Write-Host "The date is not greater than or equal to 2022-01-01."
}The Compare-Object cmdlet in PowerShell
Apart from the basic comparison operators, PowerShell provides advanced techniques for comparison. One such technique is using the Compare-Object cmdlet, which allows you to compare two sets of objects and identify the differences between them.
The Compare-Object command is particularly useful when you need to compare complex objects or compare objects based on specific properties. It provides options to specify the properties to compare, the comparison mode (exact, ignore case, or ignore whitespace), and more.
Example: Comparing Two Arrays using Compare-Object in PowerShell
$set1 = @(1, 2, 3, 4)
$set2 = @(2, 3, 4, 5)
$comparisonResult = Compare-Object $set1 $set2
if ($comparisonResult.Count -eq 0) { Write-Host "The sets of objects are identical."
} else { Write-Host "The sets of objects are different."
}How to Master PowerShell Comparison Operators?
Mastering PowerShell comparison operators is crucial for effective scripting and automation. In this comprehensive guide, We have explored everything you need to know about PowerShell comparison operators, including their benefits, and advanced techniques for using them effectively.
What are comparison operators in PowerShell?
Comparison operators in PowerShell compare values and return a Boolean result (true or false) based on the comparison. You can use them in conditional statements, loops, and filters to make decisions by comparing values.
What is the difference between -eq and -like?
The -eq operator is used to compare exact matches, while the -like operator is used to compare partial matches using wildcards.#Using -eq operator
"Hello, World" -eq "Hello, World" # Returns True
#Using -like operator
"Hello, World" -like "Hello*" # Returns True
Can I use PowerShell comparison operators with arrays?
Yes, you can use comparison operators with arrays to compare values. #Define arrays
$array1 = 1,2,3,4,5
$array2 = 1,2,3,4,5
#Compare arrays
$result = (Compare-Object -ReferenceObject $array1 -DifferenceObject $array2) -eq $null
#Output result
$result # Returns True as two arrays are equal
What is the not match operator in PowerShell?
What are the boolean comparison operators in PowerShell?
In PowerShell, the primary boolean comparison operators are -and, -or, and -not. Here’s an example:#Define boolean values
$bool1 = $true
$bool2 = $false
#Using -and operator
$bool1 -and $bool2 # Returns False
#Using -or operator
$bool1 -or $bool2 # Returns True
#Using -not operator
-not $bool1 # Returns False
-not $bool2 # Returns True
How do I check if two values are equal in PowerShell?
How do I check if two strings are equal in PowerShell?
In PowerShell, you can compare two strings for equality using the -eq operator. Here’s a simple example:"Hello, World" -eq "Hello, World" # Returns True
How can I check if a string matches a specific pattern using wildcard characters in PowerShell?
How do I check if a collection in PowerShell contains a value?
How can I check the type of an object in PowerShell?
How do you use the -match operator?
The -match operator uses regular expressions to compare strings, checking if the string on the left matches the pattern on the right. For example, 'PowerShell' -match '^P.*ll$' returns True because “PowerShell” starts with ‘P’ and ends with ‘ll’.


