我想使用 PowerShell 打开存储在 Sharepoint 2010 文档库中的 XML 文档,将其读入内存,修改其中一个节点,然后将修改后的 XML 保存回去,覆盖原始文档。我宁愿不写任何本地文件;我真的不认为这是必要的。
这是我现在的脚本:
param
(
$siteCollection = $(read-host -prompt "Site Collection"),
$subSite = "StoreOps",
$libraryName = "Data Connections",
$UDCXName = $(read-host -prompt "UDCX document name"),
$listName = $(read-host -prompt "List name")
)
$site = get-spsite $siteCollection
$web = $site.openweb($subSite)
$library = $web.Folders[$libraryName]
$document = $library.Files[$UDCXName]
# Load the contents of the document.
$data = $document.OpenBinary()
$encode = New-Object System.Text.ASCIIEncoding
$UDCX = [xml]($encode.GetString($data))
$ns = New-Object Xml.XmlNamespaceManager $UDCX.NameTable
$ns.AddNamespace("udc", "http://schemas.microsoft.com/office/infopath/2006/udc")
$root = $UDCX.DataSource
$node = $root.SelectSingleNode("udc:ConnectionInfo/udc:SelectCommand/udc:ListId", $ns)
$oldListId = $node."#text"
# Get the ListId of the current list.
$list = $web.Lists[$listName]
$newListId = "{$($list.ID)}"
write-host "List: $listName, Old ListId: $oldListId, New ListId: $newListId"
$node."#text" = $newListId
(对于那些感兴趣的人,此脚本将修改 InfoPath 表单使用的数据连接文件)。
所有这些脚本都可以正常工作,但现在我该如何将 XML 重写回 Sharepoint?我试过:
$document.SaveBinary($UDCX.xml)
但这行不通。我对如何让 $UDCX xml 对象生成它包含的 xml 的文本表示有点困惑。如果我知道该怎么做,那么我就能解决这个问题。
最佳答案
$Document
是使用 OpenBinary()
方法打开的,因此要直接保存回它,我们需要使用 SaveBinary()
方法。 XMLDocument 对象 $UDCX
可以保存到 MemoryStream
对象,然后使用该对象直接保存回 Sharepoint。最后需要的代码如下:
$Stream = New-Object System.IO.MemoryStream
$UDCX.Save($Stream)
$document.SaveBinary($Stream.ToArray())
希望对您有所帮助。
关于xml - 使用powershell读取/修改/重写sharepoint xml文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14905396/