Author Posts

July 26, 2017 at 2:09 pm

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
}

July 26, 2017 at 2:11 pm

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.

July 26, 2017 at 2:48 pm

[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"}

July 26, 2017 at 4:26 pm

if it evaluates to true or false, yes.

July 26, 2017 at 4:30 pm

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
}

July 26, 2017 at 7:06 pm

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

July 26, 2017 at 7:54 pm

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