You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Pnp.PowerShell创建SharePoint Online列表项无报错却未生效问题

问题原因

你当前使用SharePoint CSOM原生对象操作列表项,所有对$new_item的修改和Update()调用都仅在本地内存中生效,并未向SharePoint Online服务端提交变更请求,因此不会实际创建列表项,返回的ID为-1就是客户端未提交对象的默认临时值。

解决方案

方案1:修改现有CSOM风格代码,补充提交请求

在$new_item.Update()后添加Invoke-PnPQuery,将本地变更提交到服务端,修正后的代码如下:

## ... urls and security creds removed... 
Connect-PnPOnline -Url $km_site -ClientId $clientid -ClientSecret $secret -WarningAction Ignore
[Microsoft.SharePoint.Client.List]$projects_list = Get-PnPList "Projects"
Write-Host $projects_list.Title -ForegroundColor Green
$lci = New-Object Microsoft.SharePoint.Client.ListItemCreationInformation -ArgumentList @()
[Microsoft.SharePoint.Client.ListItem]$new_item = $projects_list.AddItem($lci)
$new_item["Title"] = $title
$new_item["Project_x0020_Code"] = $code
$new_item["_ExtendedDescription"] = $desc
$new_item["ContentTypeId"] = "0x010097F10B16E4516A4E80FC5C8FABF9BAC400AEEB05A0E486404FA588439EADC25541"
$new_item.Update()
# 新增以下行提交变更到服务端
Invoke-PnPQuery
Write-Host "Created!!" -ForegroundColor Yellow
Write-Host $new_item.Id -ForegroundColor Yellow

提交完成后你再读取$new_item.Id就会返回服务端生成的真实列表项ID。

方案2:使用PnP.PowerShell原生Cmdlet(更简洁,推荐)

直接用Add-PnPListItem无需手动处理CSOM对象逻辑,示例代码如下:

Connect-PnPOnline -Url $km_site -ClientId $clientid -ClientSecret $secret -WarningAction Ignore
$new_item = Add-PnPListItem -List "Projects" -ContentType "0x010097F10B16E4516A4E80FC5C8FABF9BAC400AEEB05A0E486404FA588439EADC25541" -Values @{
    "Title" = $title
    "Project_x0020_Code" = $code
    "_ExtendedDescription" = $desc
}
Write-Host "创建成功,列表项ID:$($new_item.Id)" -ForegroundColor Green
注意事项
  • 提前确认$title、$code两个必填字段的变量已正确赋值,不能为空值
  • 确认你使用的自定义内容类型ID正确,且该内容类型已添加到「Projects」列表的可用内容类型中
  • 确认你使用的客户端ID对应应用注册已授予SharePoint列表的写入权限

内容的提问来源于stack exchange,提问作者Glenn Ferrie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 16:57:01