mmj
mmj

Reputation: 5780

Using powershell from a batch script

I want to take advantage of powershell to make some simple math calculations inside a batch script. I'm able to calculate a floating point division in a batch script with

set numerator=3.5
for /f %%i in ('powershell 10/%numerator%') do (set result=%%i)

which correctly sets the result variable to 2.85714285714286, but I was not able to call from the batch script a powershell command like powershell [math]::max(3,4), which returns the maximum of two numbers. Calling

for /f %%i in ('powershell [math]::max^(3,4^)') do (set result=%%i)

from a batch script sets the result variable to +.

Thanks in advance for any help.

Upvotes: 0

Views: 401

Answers (1)

SomethingDark
SomethingDark

Reputation: 14304

The , needs to be escaped as well. Otherwise, you get the powershell error

At line:1 char:14
+ [math]::max(3 4)
+ ~
Missing ')' in method call.
At line:1 char:15
+ [math]::max(3 4)
+ ~
Unexpected token '4' in expression or statement.
At line:1 char:16
+ [math]::max(3 4)
+ ~
Unexpected token ')' in expression or statement.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordEx ception
+ FullyQualifiedErrorId : MissingEndParenthesisInMethodCall

And because strings are tokenized by default in for /f loops, the result is +.


In summary, just escape the comma.

for /f %%i in ('powershell [math]::max^(3^,4^)') do (set result=%%i)

Upvotes: 1

Related Questions