将哈希表数组中的元素移动到 PowerShell 中的另一个数组
Move elements in an array of hashtables to another array in 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
然后从 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)
您可以像这样围绕此操作包装一个函数(使用引用调用):
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'}
或以上的组合。
PS 4.0 使用 Where
方法:
$b, $a = $a.Where({$_.s -Eq 'b'}, 'Split')
更多信息:
我想将哈希表从一个数组移动到另一个数组。
假设我有一个哈希表数组:
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)
您可以像这样围绕此操作包装一个函数(使用引用调用):
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'}
或以上的组合。
PS 4.0 使用 Where
方法:
$b, $a = $a.Where({$_.s -Eq 'b'}, 'Split')
更多信息: