Retrieving Condition from a Variable

This topic contains 7 replies, has 4 voices, and was last updated by  Chris Bakker 3 weeks ago.

  • Author
    Posts
  • #75935

    Malik Amaduddin
    Participant

    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
    }

  • #75937

    Don Jones
    Keymaster

    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.

  • #75944

    Chris Bakker
    Participant

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

    • #75949

      Don Jones
      Keymaster

      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
      }
      
    • #75955

      Malik Amaduddin
      Participant

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

    • #75961

      Chris Bakker
      Participant

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

  • #75947

    Dan Potter
    Participant

    if it evaluates to true or false, yes.

You must be logged in to reply to this topic.