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

请求编写PowerShell脚本:提取含元数据URL并更新SharePoint属性

PowerShell脚本:提取TXT信息并同步SharePoint文件与元数据

前提准备

  1. 安装PnP.PowerShell模块(用于SharePoint操作):
Install-Module -Name PnP.PowerShell -Force -AllowClobber
  1. 确保你的TXT文件格式为每行一条记录,结构是:日期,ID,文件URL,示例:
20/01/2023 8:30:01 AM,12456,https://example.com/report.pdf
21/01/2023 2:15:00 PM,12457,https://example.com/data.xlsx

完整脚本

# 配置参数 - 根据你的实际环境修改
$txtFilePath = "C:\Files\FileList.txt"
$siteUrl = "https://yourtenant.sharepoint.com/sites/YourSite"
$libraryName = "Documents"
# 替换为文档库中对应字段的内部名称
$dateFieldInternalName = "DocumentCreatedDate"
$idFieldInternalName = "DocumentReferenceID"

# 连接到SharePoint站点(交互式登录)
Connect-PnPOnline -Url $siteUrl -Interactive

# 读取TXT文件中的所有条目
$fileEntries = Get-Content -Path $txtFilePath

# 循环处理每条记录
foreach ($entry in $fileEntries) {
    # 分割条目(处理未转义的逗号,限制分割为3部分)
    $parts = $entry -split '(?<!\\),', 3
    if ($parts.Count -ne 3) {
        Write-Warning "无效记录,跳过:$entry"
        continue
    }

    # 提取并清理字段值
    $rawDate = $parts[0].Trim()
    $docId = $parts[1].Trim()
    $sourceFileUrl = $parts[2].Trim()

    # 解析日期为DateTime对象(适配TXT中的格式)
    try {
        $docDate = [DateTime]::ParseExact($rawDate, "dd/MM/yyyy h:mm:ss tt", [System.Globalization.CultureInfo]::InvariantCulture)
    }
    catch {
        Write-Warning "日期解析失败,跳过记录:$entry,错误:$($_.Exception.Message)"
        continue
    }

    # 生成临时文件路径
    $tempFileName = [System.IO.Path]::GetFileName($sourceFileUrl)
    $tempFilePath = Join-Path -Path $env:TEMP -ChildPath $tempFileName

    try {
        # 下载源文件
        Invoke-WebRequest -Uri $sourceFileUrl -OutFile $tempFilePath -ErrorAction Stop
        Write-Host "已下载:$tempFileName"

        # 上传文件到SharePoint文档库
        $uploadedItem = Add-PnPFile -Path $tempFilePath -Folder $libraryName -ErrorAction Stop
        Write-Host "已上传至SharePoint:$($uploadedItem.ServerRelativeUrl)"

        # 更新文件元数据
        Set-PnPListItem -List $libraryName -Identity $uploadedItem.ListItemAllFields.Id -Values @{
            $dateFieldInternalName = $docDate
            $idFieldInternalName = $docId
        } -ErrorAction Stop
        Write-Host "已更新元数据:ID=$docId,日期=$docDate`n"
    }
    catch {
        Write-Error "处理记录失败:$entry,错误信息:$($_.Exception.Message)"
    }
    finally {
        # 清理临时文件
        if (Test-Path -Path $tempFilePath) {
            Remove-Item -Path $tempFilePath -Force
        }
    }
}

# 断开SharePoint连接
Disconnect-PnPOnline

关键说明

  • 字段内部名称:在SharePoint文档库的「设置」→「列」中,点击目标列,地址栏中Field=后面的字符串就是内部名称(例如DocumentCreatedDate),必须使用内部名称才能正确更新元数据。
  • 日期格式适配:如果你的TXT文件日期格式不同,修改ParseExact中的格式字符串,比如美式日期MM/dd/yyyy对应"MM/dd/yyyy h:mm:ss tt"。
  • 权限要求:运行脚本的账号需要拥有SharePoint文档库的编辑权限,以及源文件URL的访问权限。
  • 错误处理:脚本会自动跳过格式无效或处理失败的记录,并输出警告/错误信息,便于排查问题。

内容的提问来源于stack exchange,提问作者Divya Nair

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 20:25:57