将API结果合并到Powershell中的单个对象中

问题描述

我有两个API端点来命中和检索用户信息,并将数据写入sql表。端点在URL中使用员工ID,因此我遍历每个用户获取其数据。端点2包含用户的“自定义字段”。我正在尝试合并两个端点的返回值,并在sql表中为每个用户将它们写为一行。

它们将PSCustomObject作为哈希表返回。 端点1:cat6注意属性字符串cat6 = NONE

端点2:CustomText94 NoteProperty System.Management.Automation.PSCustomObject CustomText94 = @ {description =;值=}

function Export-Feed {

    Begin {
        $serverInstance = ""
        $database = ""
        $tableName = ""
        $employees = Get-Directory | Where-Object eestatus -eq A
    }

    Process {
        $result = $employees | ForEach-Object -Parallel {
            $params = @(
                'firstname','middlename','lastname',@{n='ADID';e={(Connect-Api -apiEndpoint "/api/v1/employee/$($_.eecode)/customfield").CustomText04.value}},'hire_date','rehire_date','position_title','termination_date','work_email','employee_code','clocksequencenumber','department_code','department_description','employee_status','supervisor_primary','supervisor_primary_code','supervisor_secondary','supervisor_secondary_code','supervisor_tertiary','supervisor_tertiary_code','supervisor_quaternary','cat1','cat1desc','cat2','cat2desc','cat3','cat3desc','cat4','cat4desc','cat5','cat5desc','cat6','cat6desc','cat7','cat7desc','cat8','cat8desc','cat9','cat9desc'
            )


            Connect-Api -apiEndpoint "/api/v1/employee/$($_.eecode)" | Select-Object $params

        }
    }
    
    End {
        $result | Out-File c:\temp\test.txt
        #Write-sqlTableData -DatabaseName $database -TableName $tableName -ServerInstance $serverInstance -SchemaName dbo -InputData $result -force 
    }
}

解决方法

要合并两个自定义对象([pscustomobject]实例,它们与哈希表不同),请使用以下技术:

# Two sample input objects.
$o1 = [pscustomobject] @{ one  = 1; two  = 2; three = 3 }
$o2 = [pscustomobject] @{ four = 4; five = 5; six   = 6 }

# Merge the two,by appending the properties of the 2nd to the 1st.
# Note: This assumes that there is no overlap between the property names.
foreach ($prop in $o2.psobject.Properties) {
  $o1.psobject.Properties.Add($prop,$true)
}

# $o1 now contains the union of both property sets; 
# Output it.
$o1 | Format-Table

以上结果:

one two three four five six
--- --- ----- ---- ---- ---
  1   2     3    4    5   6

以上内容依赖于PowerShell中具有隐藏的.psobject属性的每个对象,该属性提供有关该对象的反射信息,尤其是.Properties属性返回的所有属性的集合。

PowerShell允许将属性动态添加到任何属性,这是其ETS (Extended Type System)的功能。 [pscustomobject]个实例仅包含 这样的动态属性。 .Add()方法允许将另一个对象的属性的副本添加到一个对象。 $true表示无需执行验证,从而加快了操作速度。