我注意到编写 PowerShell 类行时发生了一件有趣而奇怪的事情:
class A {
[object] WhereObject(){
return @(1,2) | Where-Object {$_ -gt 2}
}
[object] Where(){
return @(1,2).Where( {$_ -gt 2})
}
}
$a = new-object A
$a.WhereObject() # Throw exception Index was out of range. Must be non-negative and less than the size of the collection.
$a.Where() # Works well
Run Code Online (Sandbox Code Playgroud)
看起来它是设计使然。为什么会这样?
解决方法
将“空”值显式转换为 $null 的函数:
function Get-NullIfEmpty {
param(
[Parameter(ValueFromPipeline=$true)][array] $CollectionOrEmtpy
)
begin { $output = $null }
process
{
if($output -eq $null -and $CollectionOrEmtpy -ne $null){ …Run Code Online (Sandbox Code Playgroud) powershell ×1