This post will overview several techniques to fix the mentioned query.
How to Compare Two String Objects’ Content in PowerShell?
These approaches can be used to compare the two objects:
Method 1: Use “like” Operator to Compare Two String Objects’ Content
“-like” is a type of comparison operator used to compare the two values such as strings, variables, or constants. If the specified values get matched, its outputs “True”. Else, it returns “False”.
Example 1: Comparing the Same Content of Two String Objects
First, we have assigned the string values to three different variables. After that, we will compare these strings assigned variables using the “-like” operator:
$b = 'Hi people'
$c = 'Hello world'
$a -like $c
Output
The like operator returned output “True” because the value of both “$a” and “$c” variables are the same.
Example 2: Comparing the Different Content of Two String Objects in PowerShell
Now, let’s compare the two variables whose values are not the same:
$b = 'Hi people'
$c = 'Hello world'
$a -like $b
As both of the specified variables have different values, so the like operator will return “False”:
Method 2: Comparing the Contents of Two String Objects in PowerShell Using “Equals()” Method
Another method for the comparison of the two string objects using the “Equals()” method. It will create a comparison of two values. Likewise, it returns the boolean value “True” or “False” based on the same or different values of the declared strings.
Example
This example will compare the string values using the “Equals()” method:
$b = 'Hi people'
$c = 'Hello world'
$a.Equals($c)
Output
Method 3: Use “-eq” Operator to Compare Two String Objects’ Content
The “-eq” operator is one of the comparison operators used to compare the two values. If the values are matching then the resultant output will be “True”, else the output will be “False”.
Example
This example will compare the two string values using the “eq” operator:
$b = 'Hi people'
$c = 'Hello world'
$a -eq $c
Output
The output is “True” because the specified string values are the same.
Conclusion
In PowerShell, to compare two string objects’ content, first, assign strings to more than one variable. After that, compare the variables containing the string values by using the “-eq” operator, “-like” operator, or “Equals()” method. If the string values are matching then the resultant output will be “True”, else the resultant output will be “False”. This post has explained the procedure to fix the mentioned query.