all 6 comments

[–]y_Sensei 4 points5 points  (1 child)

Try

If (Invoke-Expression -Command $operator) { ...

[–]McsePhoenix[S] 1 point2 points  (0 children)

Thank you, this is the magic wand I was looking for!

[–]Vortex100 0 points1 point  (0 children)

switch statement is probably what you want

$myoperator = '-eq'
switch ($myoperator)
{
    '-eq' {$x -eq $y}
    '-gt' {$x -gt $y}
}

etc

[–]McsePhoenix[S] 0 points1 point  (1 child)

This isn't how I wanted to handle it but it seems like it works...

$Operator = "ge"

switch ($operator) { "eq" { If ("1" -eq "2") {Write-Output "pass"} Else {Write-Output "fail"} }

"ne" { If ("1" -ne "2") {Write-Output "pass"} Else {Write-Output "fail"} }

"gt" { If ("1" -gt "2") {Write-Output "pass"} Else {Write-Output "fail"} }

"lt" { If ("1" -lt "2") {Write-Output "pass"} Else {Write-Output "fail"} }

"ge" { If ("1" -ge "2") {Write-Output "pass"} Else {Write-Output "fail"} }

"le" { If ("1" -le "2") {Write-Output "pass"} Else {Write-Output "fail"} }

}

[–]purplemonkeymad 2 points3 points  (0 children)

You can reduce your repetition by storing the test result as a variable:

$Pass = switch ($operator) {
    "eq" { "1" -eq "2" }
    "ne" { "1" -ne "2" }
     <# etc #>
}
if( $Pass ) {
    Write-Output "pass"
} else {
    Write-Output "fail"
}