0

In PowerShell, how do I evaluate a mathematical expression stored as a string? How do I get PowerShell to evaluate the following:

C:\> $a="30000/1001"
C:\> $a

30000/1000
C:\>

Desired output:

C:\> $a="30000/1001"
C:\> <some command>

29.97002997003
C:\>

In Linux I could do the following (and is basically what I want to accomplish in PowerShell):

user@computer:/path# a="30000/1001"
user@computer:/path# echo "scale=5; $a" | bc
29.97002
phuclv
  • 30,396
  • 15
  • 136
  • 260
Brian
  • 1,085

2 Answers2

3

Using Invoke-Expression is generally not recommended; I suggest a safer approach using System.Data.DataTable instead:

$a="30000/1001"
[Data.DataTable]::New().Compute($a, $null)
# Result = 29.97002997003
Maybe
  • 170
1

Use Invoke-Expression. Alternatively just invoke a new shell (much slower of course)

$a="30000/1001"
Invoke-Expression $a
powershell -Com $a
phuclv
  • 30,396
  • 15
  • 136
  • 260