[英]Using powershell to read/modify/rewrite sharepoint xml document
I would like to use PowerShell to open an XML document stored in a document library in Sharepoint 2010, read it into memory, modify one of the nodes and then save the modified XML back, overwriting the original document. 我想使用PowerShell在Sharepoint 2010中打开存储在文档库中的XML文档,将其读入内存,修改其中一个节点,然后将修改后的XML保存回去,以覆盖原始文档。 I'd rather not write any local files;
我宁愿不写任何本地文件; I really don't think this is necessary.
我真的没有必要这样做。
Here is the script as I have it now: 这是我现在拥有的脚本:
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
(For those of you who are interested, this script will modify data connection files used by InfoPath forms). (对于感兴趣的人,此脚本将修改InfoPath表单使用的数据连接文件)。
All of this script works correctly, but now how do I re-write the XML back to Sharepoint? 所有这些脚本都能正常工作,但是现在如何将XML重新写回到Sharepoint? I have tried:
我试过了:
$document.SaveBinary($UDCX.xml)
But this does not work. 但这是行不通的。 I'm a bit confused at how to get the $UDCX xml object to produce a text representation of the xml it contains.
我对如何获取$ UDCX xml对象以生成其包含的xml的文本表示感到有些困惑。 If I knew how to do that, then i could solve this problem.
如果我知道该怎么做,那么我可以解决这个问题。
The $Document
was opened using the OpenBinary()
method, so to save straight back to it we'd need to use the SaveBinary()
method. $Document
是使用OpenBinary()
方法打开的,因此要直接保存到它,我们需要使用SaveBinary()
方法。 The XMLDocument object, $UDCX
, can be saved to a MemoryStream
object which is then used to save straight back to Sharepoint. 可以将XMLDocument对象
$UDCX
保存到MemoryStream
对象,然后将其用于直接保存回Sharepoint。 The code you need at the end is as follows: 最后需要的代码如下:
$Stream = New-Object System.IO.MemoryStream
$UDCX.Save($Stream)
$document.SaveBinary($Stream.ToArray())
I hope that helps. 希望对您有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.