locked
How to subtract a specific value in an object's property? RRS feed

  • Question

  • Let's say I have an object called $data wich contains the following

      name    stock  
     ------- ------- 
      item1      10  
      item2      10  
      item3      10  

    How do I subtract by 1 item2 stock value ?

    I tried with this :

    $data.stock = $data.stock - 1 | Where-Object name -contains "item2"

    But I get the following error :

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

    Sunday, May 13, 2018 3:58 PM

All replies

  • 14MAY2018:122713 /:>$data.GetEnumerator()|select @{l='Name';e={$_.Key}},@{l='Stock';e={$_.value}}
    
    Name  Stock
    ----  -----
    item2     9
    item3    10
    item1    10
    
    
    14MAY2018:122758 /:>$data.Item('item2') = $data.Item('item2') - 1
    14MAY2018:122801 /:>$data.GetEnumerator()|select @{l='Name';e={$_.Key}},@{l='Stock';e={$_.value}}
    
    Name  Stock
    ----  -----
    item2     8
    item3    10
    item1    10
    
    
    14MAY2018:122802 /:>$data.GetType()
    
    IsPublic IsSerial Name                                     BaseType
    -------- -------- ----                                     --------
    True     True     Hashtable                                System.Object



    -KT

    Sunday, May 13, 2018 6:59 PM
  • I suppose you could try this if $data is just an unordered array of other objects:

    $x = $data | Where-Object name -contains 'Item2'
    $x -= 1


    --- Rich Matheisen MCSE&I, Exchange Ex-MVP (16 years)

    Sunday, May 13, 2018 7:16 PM
  • Many good guesses but here is how to do this:

     $data | Where-Object{$_.name -eq 'Item2'} | ForEach-Object{$_.Stock = $_.Stock -1 }


    \_(ツ)_/



    • Edited by jrv Sunday, May 13, 2018 8:56 PM
    Sunday, May 13, 2018 8:55 PM
  • Almost the same thing.

    $data | where name -eq item2 | foreach { $_.stock -= 1 }

    • Edited by JS2010 Monday, May 14, 2018 5:20 PM
    Monday, May 14, 2018 3:41 PM