2013-02-16 80 views
3

我想用PowerShell来打开存储在文档库中,2010年的SharePoint的XML文档,将它读入内存中,修改节点之一,然后保存修改后的XML回来,覆盖原始文件。我宁愿不写任何本地文件;我真的不认为这是必要的。使用PowerShell来读取/修改/改写的SharePoint 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的文本表示感到困惑。如果我知道如何做到这一点,那么我可以解决这个问题。

+0

看起来像它会帮助 - http://stackoverflow.com/questions/13401722/open-xml-from-sharepoint-document-library-in-poweshell – 2013-02-16 03:27:13

回答

2

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

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

我希望有所帮助。

+0

谢谢,这是工作。 – 2013-04-03 14:07:16

+0

不客气。 – 2013-04-03 19:22:36