如何使用PnP.PowerShell更新SharePoint SitePages所有WebPart文本实现翻译
解决方案
问题根源
当前代码仅覆盖了少部分WebPart的可翻译字段,不同SharePoint内置WebPart的文本字段存储位置差异较大,同时代码中存在参数传值错误会导致更新失效。
优化方案
1 修正更新参数错误
你当前调用Set-PnPPageWebPart时传入的Page参数是字符串路径,应该直接传入已获取的$newPage对象,避免页面定位错误导致的更新失效:
将原代码中Set-PnPPageWebPart -Page "$targetlanguage/$pageTitle" ...修改为Set-PnPPageWebPart -Page $newPage ...
2 补充常用未覆盖的翻译字段
大部分WebPart的标题、字幕类字段存储在以下位置,可补充到你的判断逻辑中:
- 通用标题类:
properties.title、properties.subTitle、properties.caption - 按钮类控件:
properties.buttonText、properties.linkText - 列表/汇总类控件:
properties.headerText、properties.listTitle、properties.description - 媒体类控件:
properties.tooltip - 部分WebPart的动态内容存储在
properties.serverProcessedContent节点下,需要单独遍历该节点下的字符串属性
3 更通用的全字段遍历方案
不需要逐个硬编码字段名,用递归遍历PropertiesJson下的所有字符串属性,同时过滤掉不需要翻译的字段(如路径、ID、URL类字段)即可覆盖所有WebPart的文本内容,示例逻辑如下:
# 定义不需要翻译的字段名黑名单 $excludeFields = @("id","url","imageSource","linkUrl","target","iconName","pageId","listId","itemId") function Translate-Properties { param($obj) # 遍历对象的所有属性 foreach ($prop in $obj.PSObject.Properties) { if ($excludeFields -contains $prop.Name) { continue } # 如果属性是字符串类型且非空,执行翻译 if ($prop.Value -is [string] -and $prop.Value.Trim() -ne "") { $obj.$($prop.Name) = Start-Translation -text $prop.Value -language $targetLanguage } # 如果属性是对象/数组,递归遍历 elseif ($prop.Value -is [PSCustomObject] -or $prop.Value -is [array]) { Translate-Properties -obj $prop.Value } } } # 调用方式替换原来的逐个字段判断 foreach ($WebComponent in $pageWebParts) { $properties = $WebComponent.PropertiesJson | ConvertFrom-Json Translate-Properties -obj $properties Set-PnPPageWebPart -Page $newPage -Identity $WebComponent.InstanceId -PropertiesJson ($properties | ConvertTo-Json -Depth 90) }
注意事项
- 翻译HTML格式的字段时,注意不要破坏HTML标签结构,建议先提取HTML内的纯文本翻译后再回填
- 更新完成后需要调用
$newPage.Save()和Publish-PnPClientSidePage -Identity $newPage使修改生效
内容的提问来源于stack exchange,提问作者Kayofeld
相关产品推荐
相关产品推荐

