客户端SharePoint PowerShell - 获取列表项 - 尚未初始化集合

时间:2016-06-13 11:27:16

标签: powershell sharepoint sharepoint-2013 sharepoint-clientobject

在SharePoint 2013上,我尝试使用客户端SharePoint PowerShell获取列表项。 即使对于字段ID或标题,我遇到此错误:集合尚未初始化。 我不知道如何包括字段。我在C#或JavaScript中找到许多例子,但在客户端powershell中没有。

这是我的代码(它正确返回了项目数):

Function New-Context([String]$WebUrl) {
    $context = New-Object Microsoft.SharePoint.Client.ClientContext($WebUrl)
    $context.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
    $context
}

Function Get-List([Microsoft.SharePoint.Client.ClientContext]$Context, [String]$ListTitle) {
    $list = $context.Web.Lists.GetByTitle($ListTitle)
    $context.Load($list)
    $context.ExecuteQuery()
    $list 
}

$context = New-Context -WebUrl "http://mysharepoint.com/sites/qp"
$list = Get-List -Context $context -ListTitle "QP-Configuration"

$query = [Microsoft.SharePoint.Client.CamlQuery]::CreateAllItemsQuery()
$items = $list.GetItems($query)
$context.Load($items)
$context.ExecuteQuery()

$items.Count
$items[0]

foreach($item in $items)
{
   $item.Id
}

$context.Dispose()

2 个答案:

答案 0 :(得分:1)

在按行索引获取特定列表项时:

$items[0]

或遍历Microsoft.SharePoint.Client.ListItemCollection

的集合
foreach($item in $items)
{
   #...
}

假设对象的每个属性都在PowerShell中初始化,但Microsoft.SharePoint.Client.ListItem不是这种情况,因为只能检索特定的属性子集,这就是发生此错误的原因。

要检索列表项值,我建议您通过ListItem.FieldValues属性访问它们:

#get list items values
$dataValues = @()
$items.GetEnumerator() | % { 
    $dataValues += $_.FieldValues 
}

示例

$query = [Microsoft.SharePoint.Client.CamlQuery]::CreateAllItemsQuery()
$items = $list.GetItems($query)
$context.Load($items)
$context.ExecuteQuery()

$dataValues = @()
$items.GetEnumerator() | % { 
    $dataValues += $_.FieldValues 
}

$dataValues.Count #determine the amount of items
$dataValues[0]  #access item by index

#iterate through list items and print a specific field value, for example FileRef 
foreach($item in $dataValues)
{
   $item.FileRef
}

答案 1 :(得分:0)

错误是尝试使用$items[0]或使用$item.Title代替$item["Title"]

来获取完整项目:#Import the required DLL Add-Type -Path 'C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.dll' Function New-Context([String]$WebUrl) { $context = New-Object Microsoft.SharePoint.Client.ClientContext($WebUrl) $context.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials $context } Function Get-List([Microsoft.SharePoint.Client.ClientContext]$Context, [String]$ListTitle) { $list = $context.Web.Lists.GetByTitle($ListTitle) $context.Load($list) $context.ExecuteQuery() $list } $context = New-Context -WebUrl "http://mysharepointsite.com/sites/qp" $list = Get-List -Context $context -ListTitle "QP-Configuration" $query = [Microsoft.SharePoint.Client.CamlQuery]::CreateAllItemsQuery() $items = $list.GetItems($query) $context.Load($items) $context.ExecuteQuery() $items.Count foreach($item in $items) { $item["Title"] } $context.Dispose() 或列值

正确的代码是:

scatter3