Saturday, July 14, 2012

How to loop through all SPWeb object in your SharePoint site using Powershell

If ever you need to loop through all your SPWeb object in a SharePoint site for whatever reason and you want to do it in powershell. Try out the below code snippet. It worked for me, hope it can help you.

Remove-PSSnapin Microsoft.SharePoint.PowerShell -erroraction SilentlyContinue
Add-PSSnapin Microsoft.SharePoint.PowerShell -erroraction SilentlyContinue

$siteUrl = read-host "What is your site url? Eg: http://mysharepointpotal"
$site= Get-SPSite $siteURL
$webs= $site.AllWebs
try
{
    foreach ($web in $webs)
    {
        Write-Host $web.url
       
        # Perform operation
    }
}
catch
{
    write-host -f Red "error" $_.exception
    $errorlabel = $true
}
And that's it, you can now loop through all SPWeb objects in your site.

Happy scripting :-)

Tuesday, July 3, 2012

Programatically creating a SharePoint publishing page

Creating a new SharePoint publishing page is pretty simple, we just got a couple of things to remember.

First check if the page already exists, if so you can edit that page. If it does not exist we need to pass a filename and a page layout which are pretty important.

Once the page is created you can do pretty much anything with it.

        private static PublishingPage CreatePage(string filename, string title, string siteUrl, string pageLayout)
        {
            try
            {
                using (SPSite s = new SPSite(siteUrl))
                {
                    using (SPWeb w = s.OpenWeb())
                    {
                        PublishingWeb pWeb = PublishingWeb.GetPublishingWeb(w);

                        PageLayout[] ls = pWeb.GetAvailablePageLayouts();
                        var layout = ls.ToList().Find(x => x.Title.Equals(pageLayout, StringComparison.InvariantCultureIgnoreCase));

                        if (layout == null)
                            return null;

                        var p = pWeb.GetPublishingPages().ToList().Find(x => x.Name.Equals(filename, StringComparison.InvariantCultureIgnoreCase));

                        if (p == null)
                            p = pWeb.GetPublishingPages().Add(filename, layout);
                        else
                            return p;

                        p.Title = title;
                        p.Update();

                        return p;
                    }
                }
            }
            catch
            {
                return null;
            }
        }

And there you have it you have successfuly created a new SharePoint publishing page.