powershell - 将两个 PSCustomObjects 合并为一个 - PowerShell

标签 powershell

我需要 PowerShell 的帮助,以将两个输出或两个 PSCustomObjects 合并为一个。 例如,

$services = Get-Service | Select Name, Starttype,Status
$processes = Get-Process | Select ID

我需要带表头的输出 姓名、开始类型、状态、ID

我已经尝试创建 CSV 并加入它们,但问题是当服务的整个输出结束时进程 ID 开始。我需要它们并行。

其次,我尝试创建 PSCustomObjects 但没有成功。

请帮助我处理 PowerShell 代码。

我试图实现的实际代码。

**$exclusionItems = @()
$OasHighItems = @()   
foreach($item in $items){
    $exclusionItems  += [PSCustomObject]@{
        EXCLUSION_BY_NAME_OR_LOCATION = $item.EXCLUSION_BY_NAME_OR_LOCATION
        EXCLUSION_EXCLUDE_SUBFOLDERS = $item.EXCLUSION_EXCLUDE_SUBFOLDERS
        EXCLUSION_ON_READ= $item.EXCLUSION_ON_READ
    }
    
}
foreach($oas in $oashigh){
    $oashighItems += [PSCustomObject]@{
        OAS_PROCESSES_LIST = $oas
    }
}
$Array = @()
$Array = $exclusionItems,$oashighItems
$Array | Update-FirstObjectProperties | Export-Excel $ExcelParams -TableName Table -Show**

最佳答案

我假设您想通过名称连接两个对象,即将进程名称与服务名称相匹配。为此,您可以遍历所有进程和服务,仅保留服务名称等于进程名称的那些,并使用计算属性将结果合并到一个对象中:

$services = Get-Service;
Get-Process | ForEach-Object {$p = $_;  $services |
                Where-Object{$p.ProcessName -eq $_.Name} |
                    Select-Object Name,StartType,Status,@{n='ID';e={$p.ID}}} 

我机器上的输出是:

Name                  StartType  Status    ID
----                  ---------  ------    --
CcmExec               Automatic Running 14856
CmRcService           Automatic Running  5748
FusionInventory-Agent Automatic Running  5996
IBMPMSVC              Automatic Running  3540
IntelAudioService     Automatic Running  6104
... and so on ...

关于powershell - 将两个 PSCustomObjects 合并为一个 - PowerShell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65341056/

相关文章:

c# - 如何启动一个新的 powershell 实例并在其中运行命令?

powershell - 如何将 Name NoteProperty 添加到对象?

powershell - 简单示例 : Expressions are only allowed as the first element of a pipeline

powershell - 如何从脚本中提升Powershell脚本

windows - Powershell 中的 vimdiff E97

powershell - 使用 powershell 发送 gmail

windows - 无法使用 Remove-Item -Recurse -Force 递归删除某些文件

powershell - 获取不继承权限的文件夹名称

azure - 无法在 Azure SQL 上启用读取横向扩展

powershell - 哪个 PowerShell 版本引入了给定的 cmdlet?