question

ChristopherJack-1763 avatar image
0 Votes"
ChristopherJack-1763 asked ChristopherJack-1763 commented

Maths in Powershell

Hi,

I am trying to sum the total price within Powershell using the below code

 For ($i=0; $i -le $OrderInfo.count; $i++) 
 {
     $totalprice = $totalprice + $Orderinfo[$i]."Item Price" * $Orderinfo[$i]."Item Quantity"
    
 }

However when I am running it I am getting the following error

Specified argument was out of the range of valid values.
Parameter name: times
At D:\Powershell\EDI.ps1:53 char:5
+ $totalprice = $totalprice + $Orderinfo[$i]."Item Price" * $Orderi ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], ArgumentOutOfRangeException
+ FullyQualifiedErrorId : System.ArgumentOutOfRangeException

Example data below. Any help appreciated.

Item Quantity Item Price
1 82
1 12
1 0
1 68
1 0
1 0
6 1
1 -6
-6 1
-1 1
-1 1
-3 1
-1 1
-1 1
-1 1
-1 1
-1 1
-8 0.1
-12 24.55
-6 32.73
-12 29.09
-6 30.91
-6 29.55
-1 18
-6 0.5
-1 18
-6 0.5

windows-server-powershell
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

IanXue-MSFT avatar image
0 Votes"
IanXue-MSFT answered ChristopherJack-1763 commented

Hi,

Please check the data type of the properties "Item Price" and "Item Quantity". If $Orderinfo is imported from a file, the data type of the properties should be string and have to be cast to float or double. See if this works

 For ($i=0; $i -lt $OrderInfo.count; $i++) 
 {
     $totalprice = $totalprice + [float]$Orderinfo[$i]."Item Price" * [float]$Orderinfo[$i]."Item Quantity"
 }

Best Regards,
Ian Xue
============================================
If the Answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Thanks Ian, issue was due to it not being an integer

0 Votes 0 ·
cooldadtx avatar image
1 Vote"
cooldadtx answered

I should note that your for statement is using <= to count and it should be < since PS uses 0 to length - 1 for indice. Hence your last iteration through the loop doesn't get a valid value and probably is causing your issue.

For ($i=0; $i -lt $OrderInfo.count; $i++)


You can also simplify the logic down to eliminate these kinds of issues. Something like this perhaps.

$OrderInfo | Foreach { $totalprice + ($_."Item Price" * $_."Item Quantity" }
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.