gpt4 book ai didi

powershell - 为什么在Sharepoint上可见90+时List.ItemCount报告零项?

转载 作者:行者123 更新时间:2023-12-02 23:13:56 25 4
gpt4 key购买 nike

我正在编写一个脚本,以清除列表中的所有现有项目,然后再向其添加新项目。不幸的是,当我可以通过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表示列表中没有任何内容?

最佳答案

当使用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

关于powershell - 为什么在Sharepoint上可见90+时List.ItemCount报告零项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25090531/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com