Home > Mobile >  Assigning a Math Operator to a Variable - PS
Assigning a Math Operator to a Variable - PS

Time:09-17

I would like to assign a math operator ( - / *) to a variable to build dynamic expressions.

For example:

$operator1 = [char][byte]'043'
$operator2 = [char][byte]'045'
$calculation = [int](1 $operator1 20 $operator1 30 $operator1 100 $operator2 51)
Write-Host calculation

The output 100

Remembering that the variable $calculation is extensive and contains more numbers.

CodePudding user response:

You can do this with Invoke-Expression, but please remember that this is potentially dangerous

$operator1 = [char][byte]'043'
$operator2 = [char][byte]'045'

$calculation = Invoke-Expression -command "[int](1 $operator1 20 $operator1 30 $operator1 100 $operator2 51)"
Write-Host $calculation

Outputs 100

  • Related