为什么我的脚本会将对象返回两次?

时间:2015-11-27 04:04:22

标签: powershell

我正在做一些关于管道的学习实验,我已经建立了自己的3个功能:The-Getter,Do-Something,Output-Somewhere。

使用我的getter函数,我正在尝试输出只有name属性的3个对象。除了我的结果将被重复(显示两次)之外,它有点工作。

我想知道我在这里做错了什么:

function The-Getter {
[CmdletBinding()]
Param()

begin{
Write-Verbose -Message 'Entering the begin bloc of The-Getter'
$a = 'BMW X3'
$b = 'BMW X4'
$c = 'BMW X6'
}

process{
Write-Verbose -Message "Entering the process bloc of The-Getter with object $_"
$Collection = @()
$obj1 = New-Object –typename PSObject
$obj1 | Add-Member –membertype NoteProperty –name Name –value ($a) –passthru
$Collection += ($obj1)

$obj2 = New-Object –typename PSObject
$obj2 | Add-Member –membertype NoteProperty –name Name –value ($b) –passthru
$Collection += ($obj2)

$obj3 = New-Object –typename PSObject
$obj3 | Add-Member –membertype NoteProperty –name Name –value ($c) –passthru
$Collection += ($obj3)

Return $Collection
}

end{
Write-Verbose -Message 'Entering the end bloc of The-Getter'
}
}

输出是:

PS C:\> The-Getter

Name
----
BMW X3
BMW X4
BMW X6
BMW X3
BMW X4
BMW X6

感谢您的时间。

1 个答案:

答案 0 :(得分:1)

问题来自您调用Add-Member并返回Object。由于您不对返回的对象执行任何操作,因此会打印。

如果您将$Collection +=Add-Member行合并,问题就会消失:

$obj2 = New-Object –typename PSObject
$Collection += $obj2 | Add-Member –membertype NoteProperty –name Name –value ($b) –passthru

但实际上,你可以完全摆脱$Collection

process{
Write-Verbose -Message "Entering the process bloc of The-Getter with object $_"
$obj1 = New-Object –typename PSObject
$obj1 | Add-Member –membertype NoteProperty –name Name –value ($a) –passthru
$obj2 = New-Object –typename PSObject
$obj2 | Add-Member –membertype NoteProperty –name Name –value ($b) –passthru
$obj3 = New-Object –typename PSObject
$obj3 | Add-Member –membertype NoteProperty –name Name –value ($c) –passthru
}