Retrieving Condition from a Variable

Is there a possibility for me to retrieve a IF condition from a variable. I want to store conditions in a database outside of the code and then retrieve the condition and put it in the IF Condition. If the condition is successful then I will perform an action as mentioned in the database. it will be something like below.

$condition = “$Obj.Title -eq ‘ABC’”

if($condition)
{

Do This

}

Not in that way, no. $condition would need to be True or False. You could potentially store the entire code block and use Invoke-Expression to evaluate it. There might be a way to cast a string as a script block, but I’m still not sure PowerShell would evaluate it as Code the way you’re asking.

[bool]$a= “A” -eq “A”
if ($a) {“ok”}
ok
[bool]$a= “A” -ne “A”
if ($a) {“ok”}

or:

$condition = ‘“A” -eq “A”’

if ([bool](Invoke-Expression $condition)) {“do something”}

if it evaluates to true or false, yes.

Chris, that’s not quite the question. In your case, $a is storing True or False, not the expression itself. PowerShell evaluates it and stores the result. He’s asking if there’s a way to pull a string from a database and evaluate it.

You could, but using Invoke-Expression, which does open you up to a lot of potential abuse or attacks. Assuming the condition is in $c…

if ( (Invoke-Expression $c) ) {
 # this runs if $c evaluates to True
}

Wow Cool it works! Thanks a Mil! And thanks for the heads up on the potential threats.

it does…

If the conditions are in a database, i dont see the problem.
Just secure the database and like always, know what your doing.