"在代码中使用参数时,无法在空值表达式上调用方法"

Leo*_*ett 1 parameters powershell sharepoint

我是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"
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的测试脚本:

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)
Run Code Online (Sandbox Code Playgroud)

错误发生在这一行:

$site = new-object Microsoft.SharePoint.SPSite($siteURL)
Run Code Online (Sandbox Code Playgroud)

这条线

$list = $web.Lists[$listname.ToString()]
Run Code Online (Sandbox Code Playgroud)

我在这做错了什么?

编辑:如果我将参数硬编码到模块中,它就可以了.

Ans*_*ers 5

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

$object.SomeMethod('foo', 'bar')
Run Code Online (Sandbox Code Playgroud)

在函数调用中,您将参数作为以空格分隔的列表传递:

Invoke-Function 'foo' 'bar'
                     ^
                no comma here
Run Code Online (Sandbox Code Playgroud)

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

Invoke-Function 'foo', 'bar'
Run Code Online (Sandbox Code Playgroud)

将通过用2个元素的数组'foo''bar'所述函数的第一参数.

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

$i = 1
Invoke-Function ('{0:d2}' -f $i)
Run Code Online (Sandbox Code Playgroud)

上面的内容"01"从整数值创建一个两位数的字符串$i,并将其传递给函数的第一个参数.