Powershell match exact string

PowerShell provides the “-eq” operator to match an exact string. To use it, you can compare a string variable or a string literal with the desired string. The comparison is case-insensitive by default, but you can make it case-sensitive by using the “-ceq” operator instead.

Here are a couple of examples to demonstrate the usage:

      
        $str = "Hello World"
        
        if ($str -eq "Hello World") {
          Write-Host "The string matches exactly."
        } else {
          Write-Host "The string does not match."
        }
        
        # Output: The string matches exactly.
      
    
      
        $str = "Hello World"
        
        if ($str -ceq "hello world") {
          Write-Host "The string matches exactly in a case-sensitive manner."
        } else {
          Write-Host "The string does not match."
        }
        
        # Output: The string does not match.
      
    

In the first example, the “-eq” operator is used to compare the variable “$str” with the string “Hello World”. Since they are an exact match, the code block inside the “if” statement is executed and the output “The string matches exactly.” is displayed.

In the second example, the “-ceq” operator is used to compare the variable “$str” with the string “hello world” in a case-sensitive manner. Since the cases do not match, the code block inside the “else” statement is executed and the output “The string does not match.” is displayed.

Leave a comment