Top Menu

Tuesday, May 7, 2013

PowerShell - Saving Site and Sub-site in XML file

Scenario:
I had a requirement today to get all personal sites (site collections) and the blog sites (sub-sites) under MySite Host Site and save in an XML file. 

Following powershell script does the trick for a web application: 

PowerShell Script:
Add-PSSnapin microsoft.sharepoint.powershell -ErrorAction SilentlyContinue

$webs =  Get-SPSite -webapplication "http://mysite.domain.com"
$FilePath = "C:\Temp\MySites.xml"

Write-Host Getting all MySites...

$xml = "<PersonalSite>"
Foreach ($oneweb in $webs)
{
    $web = $oneweb.RootWeb

    if ($web.WebTemplate -eq "SPSMSITEHOST" -Or $web.WebTemplate -eq "SPSPERS")
    {
        $xml = $xml + "<Site>"
        $xml = $xml + "<MySite>" + $oneweb.URL + "</MySite>"
        Write-Host "Processing:" $oneweb.URL
            
        $spWeb = Get-SPweb $oneweb.URL
        foreach($subSite in $spWeb.Webs)
        {
            if ($subSite.WebTemplate -eq "BLOG")
            {
                $xml = $xml + "<Blog>" + $subSite.URL + "</Blog>"
            }
        }
        $spWeb.Dispose()

        $xml = $xml + "</Site>"
    }    
}
$xml = $xml + "</PersonalSite>"
#Write-Host $xml

$xml | out-File -FilePath $FilePath

Write-Host "XML file has been generate."
Write-Host "Press anyke to continue..."
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")

Result (MySites.xml):
<PersonalSite>
  <Site>
    <MySite>http://mysite.domain.com/my</MySite>
  </Site>
  <Site>
    <MySite>http://mysite.domain.com/my/personal/mjackson</MySite>
    <Blog>http://mysite.domain.com/my/personal/mjackson/Blog</Blog>
  </Site>
  <Site>
    <MySite>http://mysite.domain.com/my/personal/jdoe</MySite>
    <Blog>http://mysite.domain.com/my/personal/jdoe/Blog</Blog>
  </Site>
  <Site>
    <MySite>http://mysite.domain.com/my/personal/sman</MySite>
    <Blog>http://mysite.domain.com/my/personal/sman/Blog</Blog>
  </Site>
</PersonalSite>

Official SharePoint Documentation

I have recently contributed to the official SharePoint documentation for developement. Check it out here: https://docs.microsoft.com/en-us...