简体   繁体   中英

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. 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).

All of this script works correctly, but now how do I re-write the XML back to 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. 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. The XMLDocument object, $UDCX , can be saved to a MemoryStream object which is then used to save straight back to 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM