在Powershell中确定自定义对象的范围

时间:2016-03-01 23:22:09

标签: powershell pscustomobject

所以我有一个PowerShell问题似乎应该很容易解决,但我自己很难搞清楚。

以下列程序为例:

$MyFavoriteAnimals = @()
$Pets = "Cat","Dog","Fish","Bird"
$Names = "Jeb","Rex","Sam","Roger"

For ($i=0; $i -lt 4; $i++)
{
    $NewAnimal = @{"Kind" = $Pets[$i]; "Name" = $Names[$i]}
    $MyFavoriteAnimals += New-Object pscustomobject -Property $NewAnimal
}
$MyFavoriteAnimals | FT Kind, Name -AutoSize

这很好用,并有以下输出:

Kind Name 
---- ---- 
Cat  Jeb  
Dog  Rex  
Fish Sam  
Bird Roger

...但是如果我尝试将其放入函数并将$ MyFavoriteAnimals作为全局范围放置,则New-Object命令将停止工作:

Function My-Favorite-Animals {

    $Global:MyFavoriteAnimals = @()

    $Pets = "Cat","Dog","Fish","Bird"
    $Names = "Jeb","Rex","Sam","Roger"

    For ($i=0; $i -lt 4; $i++)
    {
        $NewAnimal = @{"Kind" = $Pets[$i]; "Name" = $Names[$i]}
        $MyFavoriteAnimals += New-Object pscustomobject -Property $NewAnimal
    }

}

My-Favorite-Animals
$MyFavoriteAnimals | FT Kind, Name -AutoSize

...我收到以下错误:

Method invocation failed because [System.Management.Automation.PSObject]     does not contain a method named 'op_Addition'.
At line:13 char:9
+         $MyFavoriteAnimals += New-Object pscustomobject -Property $NewAnimal
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidOperation: (op_Addition:String) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound

1 个答案:

答案 0 :(得分:1)

指定:** $ Global:** MyFavoriteAnimals + =,如:

Function My-Favorite-Animals {

    $Global:MyFavoriteAnimals = @()

    $Pets = "Cat","Dog","Fish","Bird"
    $Names = "Jeb","Rex","Sam","Roger"

    For ($i=0; $i -lt 4; $i++)
    {
        $NewAnimal = @{"Kind" = $Pets[$i]; "Name" = $Names[$i]}
        $Global:MyFavoriteAnimals += New-Object pscustomobject -Property $NewAnimal
    }

}

My-Favorite-Animals
$MyFavoriteAnimals | FT Kind, Name -AutoSize