【问题标题】:Join/merge arrays' properties加入/合并数组的属性
【发布时间】:2014-05-12 18:17:28
【问题描述】:

我有 2 个要合并的对象,但似乎找不到解决方案

Messages                                   Name                                                                           Error
--------                                   ----                                                                           -----
{\\APPS-EUAUTO1\C$\Users\xautosqa\AppDa... test 1                                                                          True
{[APPS-EUAUTO1] [prep] Setting agent op... test 2                                                                         False

TestPlan        Script          TestCase        TestData        ErrorCount      ErrorText       DateTime        Elapsed        
--------        ------          --------        --------        ----------      ---------       --------        -------        
D:\XHostMach... D:\XHostMach... rt1             1,\a\""         1               [#ERROR#][AP... 2014-03-28 1... 0:00:18        
D:\XHostMach... D:\XHostMach... rt2             1,\a\""         0                               2014-03-28 1... 0:00:08      

我试过了:

 function Join-Object {
    Param(
       [Parameter(Position=0)]
       $First
    ,
       [Parameter(Position=1,ValueFromPipeline=$true)]
       $Second
    )
    BEGIN {
       [string[]] $p1 = $First | gm -type Properties | select -expand Name
    }
    Process {
       $Output = $First | Select $p1
       foreach($p in $Second | gm -type Properties | Where { $p1 -notcontains $_.Name } | select -expand Name) {
          Add-Member -in $Output -type NoteProperty -name $p -value $Second."$p"
       }
       $Output
    }
 } # End: Function Join-Object

$TestCases = Join-Object $TxtTestcases $RexTestcases | Select Name, TestPlan, TestCase, Script, TestData, Error, ErrorCount, ErrorText, Messages, DateTime, Elapsed

但第二个对象不存在:

Name         TestPlan     TestCase     Script       TestData            Error ErrorCount   ErrorText    Messages    DateTime   
----         --------     --------     ------       --------            ----- ----------   ---------    --------    --------   
test 1                                                                   True                           {\\APPS-...            
test 2                                                                  False                           {[APPS-E...            

我也试过了:

Function Merge-Testcase {
Param ($TxtTestcase, $RexTestcase)
    $Fields = @{            
        Name        = $TxtTestcase.Name
        TestPlan    = $RexTestcase.TestPlan
        TestCase    = $RexTestcase.TestCase
        Script      = $RexTestcase.Script
        TestData    = $RexTestcase.TestData
        IsError     = $TxtTestcase.Error
        ErrourCount = $RexTestcase.ErrorCount
        ErrorText   = $RexTestcase.ErrorText
        Messages    = $TxtTestcase.Messages
        DateTime    = $RexTestcase.DateTime
        Elapsed     = $RexTestcase.Elapsed
    }
    New-Object PSObject -Property $Fields | ConvertTo-Csv -NoTypeInformation
} # End: Function Merge-Testcase
$TestCases = Merge-Testcase -TxtTestcase $TxtTestcases -RexTestcas $RexTestcase
$TestCases | Format-Table

但我得到了这个

"Script","Name","TestCase","TestPlan","ErrorText","TestData","ErrourCount","IsError","Elapsed","DateTime","Messages"
,,,,,,,,,,

知道如何连接这两个对象吗?

【问题讨论】:

  • 好问题 - 我发布了一个包含两个潜在解决方案的答案。我想你会喜欢第二个的:)
  • 我可以发誓我在 4 或 5 天前回答了一个类似的问题。实际上,我的回答看起来与 Trevor 为您提供的第二个解决方案非常相似。您是否尝试在 SO 上已回答的问题中寻找解决方案?
  • @TheMadTechnician 是的,我尝试了一些方法,但没有任何效果,我想是因为我有数组
  • 使用这个Join-Object$Obj1 | Join $Obj2

标签: powershell


【解决方案1】:

选项 1

一种选择是将两个对象都放入HashTable,然后将其转换为PSCustomObject

 $Obj1 = (Get-Process)[0]; # Get a process
 $Obj2 = (Get-Service)[0]; # Get a service
 ($Result = [PSCustomObject]@{ Obj1 = $Obj1; Obj2 = $Obj2; });

 $Result.Obj1.Name;
 $Result.Obj2.Name;

注意:这将创建一个额外的“级别”,您必须深入研究,所以它并不理想,但它会起作用。

选项 #2

第二个选项是遍历“第二个对象”的所有属性,并使用您的示例已经显示的 Add-Member 将它们添加到“第一个对象”。

创建一个名为c:\test\test.txt的空文件,然后运行以下代码:

# Get a couple of objects (with different property names)
$Object1 = Get-Service -Name Dnscache;
$Object2 = Get-Item c:\test\test.txt;

# Get a list of the properties on both objects
$PropertyList1 = @(Get-Member -InputObject $Object1 -MemberType Properties).Name;
$PropertyList2 = Get-Member -InputObject $Object2 -MemberType Properties | Where-Object -FilterScript { $PropertyList1 -notcontains $PSItem.Name; };

# Add the properties, from the second object, to the first object
foreach ($Property in $PropertyList2) {
    Write-Host ('Adding property: {0}' -f $Property.Name);
    Add-Member -InputObject $Object1 -Name $Property.Name -MemberType NoteProperty -Value $Object2.$($Property.Name);
}

# Output the object
$Object1 | select *;

输出如下所示:

Mode                : -a---
PSChildName         : test.txt
PSDrive             : C
PSIsContainer       : False
PSParentPath        : Microsoft.PowerShell.Core\FileSystem::C:\test
PSPath              : Microsoft.PowerShell.Core\FileSystem::C:\test\test.txt
PSProvider          : Microsoft.PowerShell.Core\FileSystem
Attributes          : Archive
CreationTime        : 3/11/2014 3:06:43 PM
CreationTimeUtc     : 3/11/2014 8:06:43 PM
Directory           : C:\test
DirectoryName       : C:\test
Exists              : True
Extension           : .txt
FullName            : C:\test\test.txt
IsReadOnly          : False
LastAccessTime      : 3/11/2014 3:06:43 PM
LastAccessTimeUtc   : 3/11/2014 8:06:43 PM
LastWriteTime       : 3/11/2014 3:06:29 PM
LastWriteTimeUtc    : 3/11/2014 8:06:29 PM
Length              : 0
BaseName            : test
VersionInfo         : File:             C:\test\test.txt
                      InternalName:     
                      OriginalFilename: 
                      FileVersion:      
                      FileDescription:  
                      Product:          
                      ProductVersion:   
                      Debug:            False
                      Patched:          False
                      PreRelease:       False
                      PrivateBuild:     False
                      SpecialBuild:     False
                      Language:         

Name                : Dnscache
RequiredServices    : {nsi, Tdx}
CanPauseAndContinue : False
CanShutdown         : False
CanStop             : True
DisplayName         : DNS Client
DependentServices   : {NcaSvc}
MachineName         : .
ServiceName         : Dnscache
ServicesDependedOn  : {nsi, Tdx}
ServiceHandle       : 
Status              : Running
ServiceType         : Win32ShareProcess
Site                : 
Container           : 

查看服务和文件的属性如何同时存在于一个对象上?

【讨论】:

  • 这会获取所有各种“属性”类型(例如,许多自定义对象最终使用的 NoteProperty)吗?
  • 是的,确实如此。我使用了-MemberType Properties,其中包括NoteProperty
  • 太棒了!我将来必须走那条路,这看起来比我使用的GM|?{$_.MemberType -Match "Property"} 更干净。谢谢特雷弗!
  • @TrevorSullivan 当我运行你的代码时,我收到了这个错误Add-Member : Cannot bind argument to parameter 'Name' because it is null. At line:12 char:43,我不明白为什么
  • @ionut 你运行的是 PowerShell 4.0 版吗?这就是编写和测试代码的内容。
【解决方案2】:

您原始帖子中的主要问题似乎是 $TxtTestcases 和 $RexTestcases 是数组,每个数组都有两个对象,但是您的 Join-Object 函数不是为了枚举数组而编写的。根据我所见,如果你这样调用它,你的函数应该可以正常工作:

加入对象@($TxtTestcases)[0] @($RexTestcases)[0]

由您决定如何选择加入数组中的哪些对象,或者如果数组包含不同数量的对象,该怎么做。此处似乎没有您要“加入”的任何公共字段(如果有,您可以使用 http://blogs.msdn.com/b/powershell/archive/2012/07/13/join-object.aspx 中的 Join-Object 函数)。

【讨论】:

  • 是的,我为这个 $TestCases = @(); for($i=0; $i -lt $TxtTestcases.length;$i++) { $TestCases += Join-Object @($TxtTestcases)[$i] @($RexTestcases)[$i] }; 进行了更改,它运行良好,谢谢
【解决方案3】:
# Create two Arrays partial name 
# combine the two arrays

$Object1 = @()

# Create a PSObject with the associated properties hashtable and add to $userObj
$userObj= New-Object PSObject -Property @{
  name="Decvic-srv1"
  Share='$admin'
  Path="c:\temp"
  SizeKB=[math]::Round((200456789/1KB),2)
  Files="345"
  }

$Object1 += $userObj
$Object1

$Object2 = @()

# Create a PSObject with the associated properties hashtable and add to $userObj
$userObj= New-Object PSObject -Property @{
  name="Decvic-srv2"
  Share='$test'
  Path="c:\temp\robertp"
  SizeKB=[math]::Round((4567789/1KB),2)
  Files="1000"
  Desc="Secondary file that needs to have write acess"
  Function="1ST Function"
  }

$Object2 += $userObj
$Object2
$First = $Object1
$Second = $Object2

$Object3 = @()

# Get a list of the properties on both objects
$PropertyList1 = $Object1 | Get-Member -Type Properties | select -expand Name
$PropertyList2 = $Object2 | Get-Member -Type Properties | select -expand Name | 
Where- 
Object -FilterScript { $PropertyList1 -notcontains $PSItem.Name }

$userObj = New-Object PSObject

# Add the 1st object properties, from the second object, to the first object
foreach ($Property in $PropertyList1) {
#Write-Host ('Adding property: {0}' -f $Property)
Add-Member -InputObject $userObj -Name $Property -MemberType NoteProperty -Value 
$Object1.$($Property)
}

$Object3 += $userObj

$userObj = New-Object PSObject

# Add 2nd object the properties, from the second object, to the first object
foreach ($Property in $PropertyList2) {
# Write-Host ('Adding property: {0}' -f $Property)
Add-Member -InputObject $userObj -Name $Property -MemberType NoteProperty -Value 
$Object2.$($Property)
}

$Object3 += $userObj

# Output the object
$Object3 | select Desc, Files, Function, name, Path, Share, SizeKB | ft

【讨论】:

    【解决方案4】:

    为了安静一段时间,我正在维护一个 Join-Object cmdlet(请参阅:In Powershell, what's the best way to join two tables into one?)。
    我对这个项目的任务是保持语法尽可能简单并获得最佳性能,同时仍然尊重有关管道的 PowerShell 开发指南。
    对于@Dave Wyatt 指出的事情:

    • 似乎没有任何公共字段”:在 SQL Join 子句中,您为此使用 ON 参数,与 Join-Object cmdlet 一样,但如果您省略-On 参数,对象索引的连接就完成了。
    • 或者如果数组包含不同数量的对象怎么办”,类似于通常对相关属性的连接,您可以使用包含的代理命令控制如何处理不同的表长度@ 987654329@(别名LeftJoin)、RightJoin-Object(别名RightJoin)和FullJoin-Object(别名FullJoin)为此(见help)。

    至于这个具体问题:

    $TxtTestcases | Join-Object $RexTestcases | Format-Table *
    
    Messages                                   Name   Error TestPlan        Script          TestCase TestData ErrorCount ErrorText       DateTime   Elapsed
    --------                                   ----   ----- --------        ------          -------- -------- ---------- ---------       --------   -------
    {\\APPS-EUAUTO1\C$\Users\xautosqa\AppDa... test 1 True  D:\XHostMach... D:\XHostMach... rt1      1,\a\""  1          [#ERROR#][AP... 2014-03-28 0:00:18
    {[APPS-EUAUTO1] [prep] Setting agent op... test 2 False D:\XHostMach... D:\XHostMach... rt2      1,\a\""  0                          2014-03-28 0:00:08
    

    【讨论】:

    • 非常好的 cmdlet
    猜你喜欢
    • 2020-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-16
    • 2016-07-21
    • 1970-01-01
    相关资源
    最近更新 更多