我正在编写一个脚本,在编写新列表之前清除所有列表的现有项目。不幸的是,当我可以通过Sharepoint查看所有90个项目时,我无法弄清楚为什么我的列表报告其中包含零项目。这是我正在运行的代码:
function uploadDataFromCSV($_ctx, $_listName)
{
Write-Host "[$_listName]"
$list = $_ctx.Web.Lists.GetByTitle($_listName)
if($list.Exists){write-host "yes"}
$list.ItemCount # Always returns 0
# Clear all the items from the list if the flag has been set
if($OverwriteItems)
{
Write-Host 'Deleting contents of list'
$list.ItemCount
$listItems = $list.Items
# Delete from last to first because %REASONS%
for($index = $listItems.Count-1; $index -gt -1; $index--)
{
$listItems[$index].Delete()
}
Write-Host 'List has been reset'
}
Write-Host 'Reading CSV file'
$csv = Import-Csv "$csvDir\$_listName.csv"
$headers = $csv | Get-Member -MemberType NoteProperty | %{$_.name}
$itemsAdded = 0
foreach($line in $csv)
{
$itemCreateInfo = New-Object Microsoft.SharePoint.Client.ListItemCreationInformation
$newItem = $list.AddItem($itemCreateInfo)
# Map each value in the line to its corresponding header
$headers | % {
$statement = [scriptblock]::Create('$newItem["{0}"] = $line.{0}' -f $_)
$statement.Invoke()
}
$newItem.Update()
$itemsAdded++
}
Write-Host' Importing items'
#Add the items to the list
#$_ctx.ExecuteQuery()
Write-Host $itemsAdded 'items imported'
}
#Load .NET CSOM modules
Add-Type -Path "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
$site_url = "https://url.goes/here"
$username = "user@domain.com"
$password = ConvertTo-SecureString -AsPlainText -Force 'gibberishPassword'
#Set up the context and set its credentials
$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($site_url)
$credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($username, $password)
$ctx.Credentials = $credentials
uploadDataFromCSV $ctx "TableName"
我需要列表中的项目数量,所以我可以逐个遍历并删除它们(我知道我知道,删除列表并从模板恢复不是一个选项)。我知道我正在抓取正确的列表,因为我在脚本中添加的项目正确插入 - 脚本运行后我可以刷新Sharepoint并查看除列表的现有项目之外的新添加的项目。
为什么$list.ItemCount
说清单中没有任何内容?
答案 0 :(得分:3)
使用SharePoint CSOM以检索List之类的客户端对象或List.ItemCount property之类的属性时,必须使用ClientContext.ExecuteQuery method进行请求。
在您的情况下,由于尚未加载List对象,因此未初始化List.ItemCount property,以下示例演示了如何获取List.ItemCount property:
$list = $context.Web.Lists.GetByTitle($listName) #get List object
$context.Load($list) #prepare query to load List object
$context.ExecuteQuery() #submit query to request List Object
$itemsCount = $list.ItemCount #ItemCount property is loaded now and returns list items count