locked
Compare integers in 2 different variables RRS feed

  • Question

  • Hi all,

    I have a PowerShell script that returns 2 variables. For example $a and $b.

    Both have a property ID and Price. (and some other properties that I won't use) Now I want to calculate the difference between the prices in $a and $b that have the same ID. I was thinking of doing this with hash tables but I'm not sure how to begin.

    Hope that anyone can help me out with this, or at least give me a head start.


    • Edited by Slinkos Wednesday, March 21, 2018 5:23 PM
    Wednesday, March 21, 2018 5:22 PM

Answers

  • Sorry - typo.

    foreach($x in $a){
         $b| Where{ $x.ID -eq $_.ID} | ForEach{[float]$x.Price - [float]$_.Price }
    }


    \_(ツ)_/


    • Edited by jrv Thursday, March 22, 2018 9:00 PM
    • Marked as answer by Slinkos Thursday, March 22, 2018 9:06 PM
    Thursday, March 22, 2018 8:59 PM

All replies

  • You would have to process this in a loop.  A hash doesn't change this and is not necessary.

    Loop through $a and then compare each item with $b by ID.  When they match output the sum.

    foreach($x in $a){
         $b| Where{ $x.ID -eq $_.ID} | ForEach{$x.Price - $_.Price }
    }


    \_(ツ)_/


    Wednesday, March 21, 2018 8:37 PM
  • Thanks a lot, I have one more challenge. The property price for $a and $b is a system string. So I can't substract them. And for some reason I'm not able to convert them to a integer.

    Edit: It's even an object. That may be the problem?

    • Edited by Slinkos Thursday, March 22, 2018 11:27 AM Extra info
    Thursday, March 22, 2018 11:19 AM
  • I still didn't find the solution. It fails because it's an array and you can't substract arrays.

    Method invocation failed because [System.Object[]] does not contain a method named 'op_Subtraction'.

    Thursday, March 22, 2018 4:06 PM
  • The code I posted works with arrays.

    Yes - you cannot do math with strings.  Convert the strings to numbers.

    ForEach{[float]$b.Price - [float]$_.Price }


    \_(ツ)_/

    Thursday, March 22, 2018 8:15 PM
  • The code I posted works with arrays.

    Yes - you cannot do math with strings.  Convert the strings to numbers.

    ForEach{[float]$b.Price - [float]$_.Price }


    \_(ツ)_/

    If I add the [float] I get the following error:

    Cannot convert the "System.Object[]" value of type "System.Object[]" to type "System.Single".
    Thursday, March 22, 2018 8:51 PM
  • It's much easier to help if you post your code and perhaps a sample of the data your are working with.
    Thursday, March 22, 2018 8:55 PM
  • Sorry - typo.

    foreach($x in $a){
         $b| Where{ $x.ID -eq $_.ID} | ForEach{[float]$x.Price - [float]$_.Price }
    }


    \_(ツ)_/


    • Edited by jrv Thursday, March 22, 2018 9:00 PM
    • Marked as answer by Slinkos Thursday, March 22, 2018 9:06 PM
    Thursday, March 22, 2018 8:59 PM