0

So I have a powershell issue that seems like it should be simple to resolve, but I am having trouble figuring it out myself.

Take for instance the following program:

$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

This works fine, and has the following output:

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

...but if I try to place this into a function and scope $MyFavoriteAnimals as a global the New-Object command stops working:

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

...and I get the following error:

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
4

1 回答 1

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
于 2016-03-01T23:31:53.340 回答