2016-05-17 57 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