Home > Mobile >  How to add data into exiting PSCustomObject
How to add data into exiting PSCustomObject

Time:11-17

I created PSCustomObject that collect some data. How can I add more values to it later on?

As exmaple

Code:

$numbers  = for ($i = 0; $i -lt 2; $i  )
{ 
    [PSCustomObject]@{
        SmallNumber = Get-Random -Minimum 1 -Maximum 10
        BigNumber = Get-Random -Minimum 100 -Maximum 1000
        }
}

$numbers contain:

SmallNumber BigNumber
----------- ---------
          2       139
          9       544

My questions are:

  • How to add additional 4 as 'SmallNumber' and 123 as 'BigNumber' to existing object?
  • How to add just 5 as 'SmallNumber'.

Sample of what I want to achieve:

SmallNumber BigNumber
----------- ---------
          2       139
          9       544
          4       123
          4       

CodePudding user response:

If you set up numbers as below you should be able to just add more PSCustomObject into your object.

See this example:

$numbers = @()
$numbers  = for ($i = 0; $i -lt 2; $i  )
{ 
    [PSCustomObject]@{
        SmallNumber = Get-Random -Minimum 1 -Maximum 10
        BigNumber = Get-Random -Minimum 100 -Maximum 1000
        }
}

$numbers  = [PSCustomObject]@{
    SmallNumber = 4
    BigNumber = 123
}

$numbers  = [PSCustomObject]@{
    SmallNumber = 5
}

Now $Numbers contains:

SmallNumber BigNumber
----------- ---------
          3       422
          4       751
          4       123
          5
  • Related