Maths in Powershell

Christopher Jack 1,611 Reputation points
2021-03-23T13:02:26.663+00:00

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
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,390 questions
0 comments No comments
{count} votes

Accepted answer
  1. Ian Xue (Shanghai Wicresoft Co., Ltd.) 30,386 Reputation points Microsoft Vendor
    2021-03-24T02:09:34.483+00:00

    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 additional answer

Sort by: Most helpful
  1. Michael Taylor 48,826 Reputation points
    2021-03-23T14:49:41.58+00:00

    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" }
    
    1 person found this answer helpful.
    0 comments No comments