Using powershell to read / modify / rewrite a sharepoint xml document
I would like to use PowerShell to open an XML document stored in a document library in Sharepoint 2010, read it in memory, change one of the nodes, and then save the changed XML back, overwriting the original document. I would rather not write local files; I really don't think this is necessary.
Here is the script as I have 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 interested, this script will modify the data connection files used by InfoPath forms.)
All of this script is working correctly, but now how do I rewrite the XML back to Sharepoint? I tried:
$document.SaveBinary($UDCX.xml)
But it doesn't work. I am a bit confused about how to get the $ UDCX xml object to create a text representation of the xml it contains. If I knew how to do this, then I could solve this problem.
source to share
$Document
was opened with a method OpenBinary()
, so to save it back we need to use the method SaveBinary()
. The XMLDocument object,, $UDCX
can be saved into an object MemoryStream
, which is then used to save back to Sharepoint. The code you need at the end looks like this:
$Stream = New-Object System.IO.MemoryStream
$UDCX.Save($Stream)
$document.SaveBinary($Stream.ToArray())
I hope this helps.
source to share