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

如何通过PowerShell为SharePoint 2016本地列表添加TXT附件并查询附件字段内部名称

SharePoint 2016本地列表:PowerShell添加.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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 00:50:44