0

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.

2 Answers 2

1

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).

Sign up to request clarification or add additional context in comments.

Comments

1

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

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.