使用powershell读取/修改/重写sharepoint xml文档

时间:2013-02-16 00:06:34

标签: xml powershell sharepoint-2010

我想使用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的文本表示感到困惑。如果我知道如何做到这一点,那么我可以解决这个问题。

1 个答案:

答案 0 :(得分:2)

使用$Document方法打开了OpenBinary(),因此为了直接保存,我们需要使用SaveBinary()方法。 XMLDocument对象$UDCX可以保存到MemoryStream对象,然后用于直接保存回Sharepoint。最后需要的代码如下:

$Stream = New-Object System.IO.MemoryStream
$UDCX.Save($Stream)
$document.SaveBinary($Stream.ToArray())

我希望有所帮助。