2016-05-17 24 views
1

我想將散列表從一個陣列移動到另一個陣列。將散列表陣列中的元素移動到PowerShell中的另一個陣列

假設我有哈希表的數組:

PS> $a = @(@{s='a';e='b'}, @{s='b';e='c'}, @{s='b';e='d'}) 

Name       Value 
----       ----- 
s        a 
e        b 
s        b 
e        c 
s        b 
e        d 

我可以選擇的一組複製到另一個數組:

PS> $b = $a | ? {$_.s -Eq 'b'} 

Name       Value 
----       ----- 
s        b 
e        c 
s        b 
e        d 

然後從除去B的項目:

PS> $a = $a | ? {$b -NotContains $_} 

Name       Value 
----       ----- 
s        a 
e        b 

有沒有更簡潔的方法呢?

回答

2

我認爲,做兩個賦值用濾波器和反濾波器是在PowerShell中這樣做的最直接的方式:

$b = $a | ? {$_.s -eq 'b'}  # x == y 
$a = $a | ? {$_.s -ne 'b'}  # x != y, i.e. !(x == y) 

你可以環繞像這樣這樣操作的功能(使用調用由參考):

function Move-Elements { 
    Param(
    [Parameter(Mandatory=$true)] 
    [ref][array]$Source, 
    [Parameter(Mandatory=$true)] 
    [AllowEmptyCollection()] 
    [ref][array]$Destination, 
    [Parameter(Mandatory=$true)] 
    [scriptblock]$Filter 
) 

    $inverseFilter = [scriptblock]::Create("-not ($Filter)") 

    $Destination.Value = $Source.Value | Where-Object $Filter 
    $Source.Value  = $Source.Value | Where-Object $inverseFilter 
} 

$b = @() 
Move-Elements ([ref]$a) ([ref]$b) {$_.s -eq 'b'} 

或類似這樣的(返回陣列的列表):

function Remove-Elements { 
    Param(
    [Parameter(Mandatory=$true)] 
    [array]$Source, 
    [Parameter(Mandatory=$true)] 
    [scriptblock]$Filter 
) 

    $inverseFilter = [scriptblock]::Create("-not ($Filter)") 

    $destination = $Source | Where-Object $Filter 
    $Source  = $Source | Where-Object $inverseFilter 

    $Source, $destination 
} 

$a, $b = Remove-Elements $a {$_.s -eq 'b'} 

或以上的組合。使用

+0

優雅溶液。 – craig

相關問題