I want to create a variable that stores a type of array that is versatile enough to be able to accept new entries of variant types, and “powershell - Array.Add vs += - Stack Overflow ” appears to describe how:
$Variable = New-Object System.Collections.Generic.List[System.Object]
However, I want to be able to add its content without adding a new line to the code:
$Variable = New-Object System.Collections.Generic.List[System.Object]
$Variable += '1','Entry2'
How?
Olaf
August 21, 2022, 6:19pm
2
May I ask why you want to have it on one line?
Edit:
And just BTW. Using the +=
operator changes the type of ne variable to System.Array
Try it …
$Variable = New-Object System.Collections.Generic.List[System.Object]
$Variable.GetType()
outputs this:
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True List`1 System.Object
and after you run this:
$Variable += '1','Entry2'
$Variable.GetType()
it outputs this:
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array
To add an element to a dotNet generic list you have to use the .Add()
method.