Friday, August 17, 2012

PowerShell – SharePoint List Data to CAML Data

Here’s a handy PowerShell function that will convert an existing list instance’s data to a CAML data structure.  The output isn’t indented, but most editors like Visual Studio can do that for you.  This also doesn’t handle XML escape characters, but it would be simple enough to add if the data required it.

 

function ListDataToCamlData($webName, $listName, $fields){
    $newLine = [Environment]::NewLine
    $web = Get-SPWeb -Identity $webName
   
    $stringBuilder = New-Object -Type System.Text.StringBuilder
    $stringBuilder.Append("<Data><Rows>")
    #TODO - Handle XML escape values &amp; &quot; &lt; &gt; &apos;
    $web.Lists[$listName].Items | %{$stringBuilder.Append("<Row>"); foreach($field in $fields){$stringBuilder.AppendFormat("<Field Name=""{0}"">{1}</Field>", $field, $_.$field)}; $stringBuilder.AppendFormat("</Row>{0}", $newLine)}
    $stringBuilder.Append("</Rows></Data>")
   
    $web.Dispose()
   
    return $stringBuilder.ToString()
}

 

And here’s an example in calling it

 

ListDataToCamlData “http://www.somesite.local” "Announcements" @("ID", "Title")

No comments:

Post a Comment