Powershell chuyển đổi Array of Objects thành PSCustomObject

Sep 09 2020

Tôi muốn chuyển đổi mảng đối tượng này

Name    CIDR
----    ----
sdc-MO  10.92.18.136/20
sdc-RM  10.77.6.34/20

thành một [PSCustomObject]

sdc-MO           sdc-RM
-------           -------
{10.92.18.136/20} {10.77.6.34/20}

Vui lòng đề xuất bất kỳ cách nào dễ dàng .. Cảm ơn

Trả lời

1 MathiasR.Jessen Sep 09 2020 at 18:27

Thêm từng đối tượng vào bảng băm hoặc loại từ điển từ điển khác, sau đó sử dụng từ điển để tạo đối tượng (mỗi mục nhập sẽ trở thành một thuộc tính riêng biệt):

$array = @( [pscustomobject]@{ Name = 'sdc-MO'; CIDR = '10.92.18.136/20' } [pscustomobject]@{ Name = 'sdc-RM'; CIDR = '10.77.6.34/20' } ) # Prepare a new dictionary to hold the properties $newProperties = [ordered]@{}

foreach($inputObject in $array){
  # If we don't already have a property with the given name, 
  # create a new entry in the dictionary
  if(-not $newProperties.Contains($inputObject.Name)){
    $newProperties.Add($inputObject.Name, @())
  }

  # Add the `CIDR` value to the corresponding property name
  $newProperties[$inputObject.Name] += $inputObject.CIDR } $newObject = [pscustomobject]$newProperties

$newObject sẽ giống như những gì bạn đã mô tả trong câu hỏi:

PS C:\> $newObject

sdc-MO            sdc-RM
------            ------
{10.92.18.136/20} {10.77.6.34/20}