Share via

Powershell Replace variable with operator

Alain Jetté 21 Reputation points
2022-04-20T23:40:40.317+00:00

Hi.
I have just started using powershell. I google and search the help from powershell, but just don't seem to find what I am looking for.

Don't know how to go about this.

lets say I have this code:

$a = "-eq"
$b = "-lt"
$c = "-gt"

$op = $a

if (3 $op 3) {  #<=== How do I convert this so it see's -eq and does the operation??
    write-host "equal"

}

How can I use $op so it does the operation?
I need to convert it from string to operator?
Do I have to set the variable as something else than a string.

Thank you.

Windows for business | Windows Server | User experience | PowerShell
0 comments No comments

Answer accepted by question author

MotoX80 37,686 Reputation points
2022-04-21T00:08:27.37+00:00
 $a = "-eq"
 $b = "-lt"
 $c = "-gt"

 $op = $a

 if ((Invoke-expression "3 $op 3")) {  #<=== How do I convert this so it see's -eq and does the operation??
     write-host "equal"      
 }

Was this answer helpful?

1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.