LeonidasFett
LeonidasFett

Reputation: 3132

Getting "Cannot call a method on a null-valued expression" when working with SharePoint in Powershell

I have a VERY annoying problem. It seems Powershell thinks it's appropriate to give me an error without actually telling me what's wrong. I have tried numerous constellations of doing this, all return the same error. Very agitated because of this.

Here is my code

$managementWeb = get-spsite http://sp2013dev3:85/sites/wtpublic
$act = "Activities"
$list = $managementWeb.Lists.TryGetList($act)

The fault lies in line 3:

You cannot call a method on a null-valued expression.
At line:3 char:1
+ $list = $managementWeb.Lists.TryGetList($act)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

Does anybody see anything wrong with this?

Upvotes: 1

Views: 5588

Answers (1)

briantist
briantist

Reputation: 47862

The error means that either $managementWeb or $managementWeb.Lists is $null.

You should check that Get-SPSite was successful and actually return an object. If it has, then check whether .Lists exists/valid:

$managementWeb = get-spsite http://sp2013dev3:85/sites/wtpublic
if ($managementWeb -and $managementWeb.Lists) {
    $act = "Activities"
    $list = $managementWeb.Lists.TryGetList($act)
} else {
    # didn't work
}

Upvotes: 1

Related Questions