This creates an actual multidimensional array as the basis for generating the array of [pscustomobject]
:
# Create multidimensional array
$temp = ('PRODCT_1', 'gra-001'),
('PRODCT_11a', 'ght-001'),
('PRODCT_ca1', 'hasha-001'),
('PRODCT_ga1', '45-001'),
('PRODCT_4a1', 'aert-001'),
('PRODCT_ata41', '43-001')
# Create single-dimensional array of pscustomobject
$array = $temp | Select-Object @{ n='name'; e={ $_[0] }},
@{ n='pn'; e={ $_[1] }}
# Output to console
$array
If you prefer, you could also do it using a single statement, without a temporary variable:
$array = (
('PRODCT_1', 'gra-001'),
('PRODCT_11a', 'ght-001'),
('PRODCT_ca1', 'hasha-001'),
('PRODCT_4a1', 'aert-001'),
('PRODCT_ata41', '43-001')
) | Select-Object @{ n='name'; e={ $_[0] }}, @{ n='pn'; e={ $_[1] }}
An even more succinct alternative using the intrinsic .ForEach
method to directly create [PSCustomObject]
array elements:
$array = (
('PRODCT_1', 'gra-001'),
('PRODCT_11a', 'ght-001'),
('PRODCT_ca1', 'hasha-001'),
('PRODCT_4a1', 'aert-001'),
('PRODCT_ata41', '43-001')
).ForEach{ [PSCustomObject]@{ name = $_[0]; pn = $_[1] } }
The latter is also the most efficient way, as it doesn't involve pipeline parameter-binding overhead.
Each of these produce the same output:
name pn
---- --
PRODCT_1 gra-001
PRODCT_11a ght-001
PRODCT_ca1 hasha-001
PRODCT_ga1 45-001
PRODCT_4a1 aert-001
PRODCT_ata41 43-001
Explanation for the Select-Object
solutions:
For each "row" of $temp
, the Select-Object
command uses calculated properties to turn the array elements into object properties.
E. g. it takes the row ('PRODCT_1', 'gra-001')
, which is an array of two elements. Then @{ n='name'; e={ $_[0] }}
gets processed, which assigns the element at index 0 ('PRODCT_1'
) to property name
. Then @{ n='pn'; e={ $_[1] }}
gets processed, which assigns the element at index 1 ('gra-001'
) to property pn
.
This process gets repeated for all remaining rows and we get an array of objects stored in $array
, just like your original code does.