如何通过PowerShell为SharePoint 2016本地列表添加TXT附件并查询附件字段内部名称
一、能否通过PowerShell为列表项添加.txt附件?
完全可以,针对SharePoint 2016本地环境,可通过SharePoint Server对象模型或**CSOM(客户端对象模型)**实现,以下是两种实用脚本示例:
1. Server对象模型脚本(适用于SharePoint服务器本地运行)
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue # 配置参数 $siteUrl = "http://你的SharePoint站点地址" $listName = "目标列表名称" $itemId = 1 # 要添加附件的列表项ID $filePath = "C:\本地txt文件路径\example.txt" # 获取站点、Web和列表项 $site = Get-SPSite $siteUrl $web = $site.OpenWeb() $list = $web.Lists[$listName] $item = $list.GetItemById($itemId) # 写入附件 $item.Attachments.Add((Split-Path $filePath -Leaf), [System.IO.File]::ReadAllBytes($filePath)) $item.Update() # 释放资源 $web.Dispose() $site.Dispose() Write-Host "附件已成功添加到列表项ID $itemId"
2. CSOM脚本(支持远程/本地运行,需加载对应程序集)
# 加载SharePoint CSOM程序集(路径适配SharePoint 2016版本) Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll" Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll" # 配置参数 $siteUrl = "http://你的SharePoint站点地址" $listName = "目标列表名称" $itemId = 1 $filePath = "C:\本地txt文件路径\example.txt" $fileName = Split-Path $filePath -Leaf # 创建客户端上下文并验证身份 $ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl) $ctx.Credentials = [System.Net.CredentialCache]::DefaultCredentials # 获取目标列表项 $list = $ctx.Web.Lists.GetByTitle($listName) $item = $list.GetItemById($itemId) $ctx.Load($item) $ctx.ExecuteQuery() # 上传附件 $fileStream = New-Object System.IO.FileStream($filePath, [System.IO.FileMode]::Open) $attachmentInfo = New-Object Microsoft.SharePoint.Client.AttachmentCreationInformation $attachmentInfo.FileName = $fileName $attachmentInfo.ContentStream = $fileStream $item.AttachmentFiles.Add($attachmentInfo) $item.Update() $ctx.ExecuteQuery() # 释放资源 $fileStream.Close() $ctx.Dispose() Write-Host "附件已成功添加到列表项ID $itemId"
二、附件相关字段的内部名称
SharePoint列表的“附件”并非普通内容字段,而是关联两项核心元素:
- 标记列表项是否含附件的布尔型字段,内部名称为
Attachments(值为True表示有附件,False表示无)。 - 实际存储附件的是列表项的
AttachmentFiles集合,需通过脚本中的$item.Attachments(Server OM)或$item.AttachmentFiles(CSOM)访问操作,而非单独字段。
内容的提问来源于stack exchange,提问作者Curious Techie
相关产品推荐
相关产品推荐

