Home > OS >  How to simplify multidimension array using Powershell?
How to simplify multidimension array using Powershell?

Time:05-16

I would like to create multidimension array in powershell, I tried this way and it works, but I want to simplified it to make it there is no repetition of name and pn. Anyone can give idea please, Thanks a lot

$array = @(
    [PSCustomObject]@{name = 'PRODCT_1'; pn = 'gra-001'}
    [PSCustomObject]@{name = 'PRODCT_11a'; pn = 'ght-001'}
    [PSCustomObject]@{name = 'PRODCT_ca1'; pn = 'hasha-001'}
    [PSCustomObject]@{name = 'PRODCT_ga1'; pn = '45-001'}
    [PSCustomObject]@{name = 'PRODCT_4a1'; pn = 'aert-001'}
    [PSCustomObject]@{name = 'PRODCT_ata41'; pn = '43-001'}
  ) 

CodePudding user response:

Not really simplified but this is one way you could do it using a hash table and enumerator the key / value pairs to create new instances of PSCustomObject:

$hash = @{
    'PRODCT_1' = 'gra-001'
    'PRODCT_11a' = 'ght-001'
    'PRODCT_ca1' = 'hasha-001'
    'PRODCT_ga1' = '45-001'
    'PRODCT_4a1' = 'aert-001'
    'PRODCT_ata41' = '43-001'
}

And then you can create the instances using either .GetEnumerator():

$hash.GetEnumerator() | ForEach-Object {
    [pscustomobject]@{
        Name = $_.Key
        Pb   = $_.Value
    }
}

Or looping through the hash table Keys:

$hash.PSBase.Keys | ForEach-Object {
    [pscustomobject]@{
        Name = $_
        Pb   = $hash[$_]
    }
}

CodePudding user response:

You could use a function or scriptblock invoke. the values will be assigned positionally so you don't have to write the names (name, pn) each times.

Using a function

Function Add-product($Name, $pn) { [PSCustomObject]@{name = $Name; pn = $pn } }
  
  $array = @(
      Add-product 'PRODCT_1' 'gra-001'
      Add-product 'PRODCT_11a' 'ght-001'
      Add-product 'PRODCT_ca1' 'hasha-001'
  )

Using a scriptblock invoke

  $add = {Param($Name,$pn)  [PSCustomObject]@{name = $Name; pn = $pn}}
  $array = @(
      & $add 'PRODCT_1' 'gra-001'
      & $add 'PRODCT_11a' 'ght-001'
      & $add 'PRODCT_ca1' 'hasha-001'
  )

Using CSV formatted data

This one is just another way to do it, although I'd probably never use it in any scenario, since I prefer the flexibility of using a custom function / scriptblock. That being said, it is definitely the most compact.

$array = @'
Name,Pn
PRODCT_1,gra-001
PRODCT_11a,ght-001
PRODCT_ca1,hasha-001
'@ | ConvertFrom-Csv
  • Related