Search code examples
powershelloperatorscase-sensitive

Powershell if -eq and -ieq are case in-sensitive and serves same purpose or -ieq needs to be used in specific scenario?


if ("True" -eq "true") {
  Write-Host "Hello"
} 
else {
  Write-Host "World"
}

Output: "Hello"

if ("True" -ieq "true") {
  Write-Host "Hello"
} 
else {
  Write-Host "World"
}

Output: "Hello"

If both serve the same purpose, is there any need for -ieq?


Solution

  • Operator -ieq is just an alias (another name) for -eq, the equality operator[1], which is case-insensitive for string comparisons, as PowerShell generally is.

    As such, -ieq isn't strictly needed, but you may choose to use it to explicitly signal case-insensitivity (which the i indicates), and to contrast it with the -ceq variant of the -eq operator, which is case-sensitive (which the c indicates).

    Caveat: i- and c-prefixed variants exist for all comparison operands, (e.g., -imatch / -cmatch), but for operators such as -eq that also work with operands other than strings, the use of a prefix is ignored for non-string operands; e.g., 1 -ceq 1 and 1 -ieq 1 are the same as 1 -eq 1 and simply compare numerically.
    [char] comparison is a hybrid case: with -eq variants it mostly acts like with strings (case-insensitive, culture-invariant comparison, but, unlike with strings, Unicode equivalence between character is not recognized), whereas with -lt / -gt variants it strictly performs ordinal comparison, i.e. numerical comparison by Unicode code point - see this answer.


    [1] Technically speaking, behind the scenes, it is the other way around:
    { 'True' -eq 'true' }.Ast.EndBlock.Statements[0].PipelineElements[0].Expression.Operator yields Ieq.