Prisoner ZERO
Prisoner ZERO

Reputation: 14166

Creating Custom Function in Powershell

I'm very new to PowerHell, and am simply trying to create an (inline) function that will take-in various parameters and return a populated array. However, I keep getting the following error:

ERROR:

You cannot call a method on a null-valued expression.
At EnumerateSites.ps1:157 char:19
+         $Array.Add <<<< ($groupName)
    + CategoryInfo          : InvalidOperation: (Add:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

THE CODE LOOKS LIKE:
The "Title" variables all have valid values.

$ValidSecurityGroupSuffixes = @("Suffix A", "Suffix B", "Suffix C")

$ExpectedSecurityGroups = CreateSecurityGroupList($SPSiteCollection.RootWeb.Title, $SPWeb.Title, $ValidSecurityGroupSuffixes)

function CreateSecurityGroupList ([string] $siteCollectionName, [string] $siteName, [string[]] $suffixes) 
{
    $Array = $()

    foreach($suffix in $suffixes)
    {
        $groupName = $siteCollectionName + " - " + $siteName + " - " + $suffix
        $Array.Add($groupName)
    }

    $Array
}

ADDITIONALLY:
When I commented-out some things and just printed the variables within the Functions ForEach Loop, I get this...

"SomeCustomerName SomeSiteName System.Object[] -  - "

I should be getting this...

"CustomerName - Location - Suffix A"
"CustomerName - Location - Suffix B"
"CustomerName - Location - Suffix C"

Any insight is appreciated.

Upvotes: 0

Views: 446

Answers (2)

markg
markg

Reputation: 302

Define the function before calling it.

$ValidSecurityGroupSuffixes = @("Suffix A", "Suffix B", "Suffix C")

function CreateSecurityGroupList ([string] $siteCollectionName, [string] $siteName, [string[]] $suffixes) 
{
    $Array = @()

    foreach($suffix in $suffixes)
    {
        $groupName = $siteCollectionName + " - " + $siteName + " - " + $suffix
        $Array += $groupName
    }

    $Array
}
$ExpectedSecurityGroups = CreateSecurityGroupList $SPSiteCollection.RootWeb.Title $SPWeb.Title $ValidSecurityGroupSuffixes

(edited because, as Dane pointed out, the function wasn't called properly).

Upvotes: 1

Dane Boulton
Dane Boulton

Reputation: 1325

First off to call a multi valued function in powershell its like this:

$ExpectedSecurityGroups = CreateSecurityGroupList -siteCollectionName $SPSiteCollection.RootWeb.Title -siteName $SPWeb.Title -suffixes $ValidSecurityGroupSuffixes)

Second powershell is funky and likes the functions at the top of your code and the function call underneath:

    Function testing([string] $someText)
    {
    #do stuff and return something
    }

$returnValue = testing $imSendingTextToAFunction

Upvotes: 1

Related Questions