"You cannot call a method on a null-valued expression" 在代码中使用参数时

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

我对 PowerShell 还很陌生,目前正在编写一个脚本来备份 SharePoint 列表项。输出格式是 excel 文件。我的模块中有一种方法接受 3 个参数:SharePoint 站点 URL、列表名称和 excel 文件应保存的路径。

所以我从测试脚本中调用这个方法并传递参数。但是当我尝试实例化 Site 和 List 对象时出现错误。

这是我的模块:

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"
    }
}

这是我的测试脚本:

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)

错误发生在这一行:

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

和这一行

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

我做错了什么?

编辑:如果我将我的参数硬编码到模块中,它就可以工作。

在 PowerShell 中,括号中以逗号分隔的参数列表仅用于方法调用:

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

在函数调用中,您将参数作为 space 分隔列表传递:

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

那是因为在 PowerShell 中,逗号和括号具有特殊含义。逗号分隔数组的元素,所以

Invoke-Function 'foo', 'bar'

会将包含 'foo''bar' 两个元素的数组传递给函数的第一个参数。

括号用于计算其他表达式中的表达式:

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

上面从整数值 $i 创建了一个双位数字符串 "01" 并将其传递给函数的第一个参数。