Monthly Archives: September 2012

Get SharePoint list items and export them to XML using PowerShell

Last time I was explaining how to get sharepoint 2010 list items using powershell script. Now, lets make a step forward and export those items into an XML file:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
cls
if((Get-PSSnapin | Where {$_.Name -eq "Microsoft.SharePoint.PowerShell"}) -eq $null) {
Add-PSSnapin Microsoft.SharePoint.PowerShell;
}

$outputXmlFilePath="C:\Exports\yourfile.xml";
$webURL = "http://sharepointsite";
$listName = "listUwant2export";

$spWeb = Get-SPWeb $webURL;
$spList = $spWeb.Lists[$listName];
$spItems = $spList.GetItems();

[System.Xml.XmlTextWriter]$xml = New-Object 'System.Xml.XmlTextWriter' $outputXmlFilePath, ([Text.Encoding]::UTF8);
$xml.Formatting = "indented";
$xml.Indentation = 4;

$xml.WriteStartDocument();
$xml.WriteStartElement('root');

$spItems | ForEach-Object {

$xml.WriteStartElement('item');

$xml.WriteAttributeString("ID",$_['ID']);
$xml.WriteAttributeString("Title",$_['Title']);

$xml.WriteEndElement();
Write-Host $_['Title'];
}

$xml.WriteEndElement();

$xml.Flush();
$xml.Close();
$spWeb.Dispose();

The result will be an XML output with values as attributes.

Get items from SharePoint List using PowerShell script

For long time I wanted to dive a bit deeper into PowerShell. Hopefully I will be able to post few of the sharepoint powershell tricks here.
First one is about getting list items from a sharepoint list:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
cls
if((Get-PSSnapin | Where {$_.Name -eq "Microsoft.SharePoint.PowerShell"}) -eq $null) {
    Add-PSSnapin Microsoft.SharePoint.PowerShell;
}

$sourceWebURL = "http://sharepointsite"
$sourceListName = "mylist"

$spSourceWeb = Get-SPWeb $sourceWebURL
$spSourceList = $spSourceWeb.Lists[$sourceListName]
#$spSourceItems = $spSourceList.GetItems()
#$spSourceItems = $spSourceList.GetItemById("1")
$spSourceItems = $spSourceList.Items | where {$_['ID'] -eq 1}

$spSourceItems | ForEach-Object {
    Write-Host $_['ID']
    Write-Host $_['Title']
}

You can either get all the items with GetItems() method currently commented out or you can filter items by some parameters. Filter applied in the script above is also equal to the GetItemById(“1”) method.