LeonidasFett
LeonidasFett

Reputation: 3132

"You cannot call a method on a null-valued expression" when using parameters in code

I am fairly new to PowerShell and I am currently writing a script that does a backup of SharePoint list items. The output format is an excel file. I have one method in my module that accepts 3 parameters: the SharePoint Site URL, the List's name and the path where the excel file should be saved.

So I call this method from a test script and pass along the parameters. But I get an error when I try to instantiate both the Site and the List objects.

Here is my module:

Function Export-SPListToExcel($siteURL, $listname, $FolderToSaveTo)
{     
    Import-Modules

    $site = new-object Microsoft.SharePoint.SPSite($siteURL)

    $web = $site.OpenWeb()

    $list = $web.Lists[$listname.ToString()]

    $table = $list.Items.GetDataTable()

    $Path = $FolderToSaveTo + (Get-Date).ToString().Replace(" ", "_").Replace(":","").Replace(".","") + ".xlsx"

    $table | Export-XLSX -Path $Path -ClearSheet    
}

Function Import-Modules
{
    if(-Not (Get-Module -ListAvailable -Name "PSExcel"))
    {        
        $psd = (Split-Path -Parent $PSCommandPath) + "\PSExcel\PSExcel.psd1"
        $psm = (Split-Path -Parent $PSCommandPath) + "\PSExcel\PSExcel.psm1"
        Import-Module $psd
        Import-Module $psm
    }

    if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $null) 
    {
        Add-PSSnapin "Microsoft.SharePoint.PowerShell"
    }
}

And here is my test script:

if(-Not (Get-Module -ListAvailable -Name "SaveAsExcel"))
{
    Import-Module C:\Temp\PSExcel-master\PSExcel-master\SaveAsExcel.psm1 
}

$path = "C:\Temp\"
$url = "http://sp2013dev3:85/sites/wtpersonal"
$list = "Activities"

Export-SPListToExcel($url, $list, $path)

The error happens at this line:

$site = new-object Microsoft.SharePoint.SPSite($siteURL)

and this line

$list = $web.Lists[$listname.ToString()]

What am I doing wrong here?

EDIT: if I hard-code my parameters into the module, it works.

Upvotes: 1

Views: 1182

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200503

In PowerShell comma-separated parameter lists in parentheses are only used in method calls:

$object.SomeMethod('foo', 'bar')

In function calls you pass arguments as a space-separated list:

Invoke-Function 'foo' 'bar'
                     ^
                no comma here

That's because in PowerShell comma and parentheses have special meanings. The comma separates the elements of an array, so

Invoke-Function 'foo', 'bar'

would pass an array with the 2 elements 'foo' and 'bar' to the first parameter of the function.

Parentheses are used for evaluating expressions inside other expressions:

$i = 1
Invoke-Function ('{0:d2}' -f $i)

The above creates a double-digit string "01" from the integer value $i and passes that to the first parameter of the function.

Upvotes: 5

Related Questions