简体   繁体   中英

Powershell Passing in Array to Function Error Empty

I created an array of custom objects using the following code:

$LOTR = @()
$myObject = new-object PSObject
$myObject | Add-Member -type NoteProperty -name GroupName - Value $city.name
$myObject | Add-Member -type NoteProperty -name GroupType - Value $city.type
$LOTR += $myObject

$LOTR (after iterations):

GroupName      GroupType
----------     ----------
Aragon          Gondor
Arwen           Rivendell

I want to pass $LOTR into a function I wrote that would compare if more than one Gondor GroupType exists. Below is a funciton to check if the array passed successfully.

function Comparison {
    param ({[Parameter(Mandatory-=$True)[string[]]$myarray})
    write-host $myarray
}

My problem is that when I try to pass $LOTR I get an error Cannot bind argument to parameter 'myarray' because it is an empty array

What am I doing wrong? I've tried using forcing the function to accept empty arrays, and it is empty. But printing the $LOTR on the powershell command line returns all the values I inputted. I'm not sure where I am going wrong.

Your code works ( sort of ) if I make some changes to your syntax

$myObject | Add-Member -type NoteProperty -name GroupName - Value $city.name

Should be the following with the space removed before Value

$myObject | Add-Member -type NoteProperty -name GroupName -Value $city.name

And I updated the function to look like this. Removing the hyphen after mandatory and the curly braces. The formatting is just for readability

function Comparison{
    param (
        [Parameter(Mandatory=$True)]
        [string[]]$myarray)
    write-host $myarray
}

As to why you are casting is to a string array I dont know.

I get the following output with your test data

@{GroupName=Aragon; GroupType=Gondor} @{GroupName=Arwen; GroupType=Rivendell}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM