2013-02-16 83 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