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

1 Answer 1

1

Specify: **$Global:**MyFavoriteAnimals += , like:

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.