Arrays 将哈希表数组中的元素移动到PowerShell中的另一个数组

Arrays 将哈希表数组中的元素移动到PowerShell中的另一个数组,arrays,powershell,powershell-5.0,Arrays,Powershell,Powershell 5.0,我想将哈希表从一个数组移动到另一个数组 假设我有一个哈希表数组: PS> $a = @( @{s='a';e='b'}, @{s='b';e='c'}, @{s='b';e='d'} ) Name Value ---- ----- s a e b s

我想将哈希表从一个数组移动到另一个数组

假设我有一个哈希表数组:

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
然后从a中删除b的项目:

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

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

有更简洁的方法吗?

我认为在PowerShell中,使用筛选器和反向筛选器执行两种赋值是最简单的方法:

$b = $a | ? {$_.s -eq 'b'}       # x == y
$a = $a | ? {$_.s -ne 'b'}       # x != y, i.e. !(x == y)
您可以像这样围绕此操作包装一个函数(使用引用调用):

或者类似这样(返回数组列表):


或上述方法的组合。

PS4.0使用
其中
方法:

$b, $a = $a.Where({$_.s -Eq 'b'}, 'Split')
更多信息:


这很巧妙。
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'}
$b, $a = $a.Where({$_.s -Eq 'b'}, 'Split')