Wednesday, October 9, 2013

SharePoint Online and PowerShell: How to Get-Spweb?

Finally, your SharePoint is Online! I mean, you have got your farm running in SharePoint online.

You still have some administration\development\maintenance left for SharePoint Online. And of course, the main means that you have used to have to do your job is PowerShell.

Now, tricky questions (who thought!) - how do you run Get-Spweb in SharePoint Online?

Isn't true that we have PowerShell in SharePoint online, you might wonder?
Yes, you are right (kind of), we have SharePoint Online management shell.
But, the module microsoft.online.sharepoint.powershell only includes some basic manipulation commands on the site collection level 

Check this cool visual tool for PowerSheeling in SharePoint to see what's available in SharePoint PowerShell modules.

So, how do you proceed with the task Get-Spweb in SharePoint Online?
Through SharePoint Client Side model of course!

Here are 3 ways that deal with it:
1.Gary Lapointe module - Lapointe.SharePointOnline.PowerShell.msi
Example:
Get-SPOWeb [-Detail [<SwitchParameter>]] [-Identity [<SPOWebPipeBind>]]

2. Using standard  Microsoft.SharePoint.Client dll

Example:

$loadInfo1 = [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client")
$loadInfo2 = [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.Runtime")
$webUrl = Read-Host -Prompt "HTTPS URL for your SP Online 2013 site" 
$username = Read-Host -Prompt "Email address for logging into that site"
$password = Read-Host -Prompt "Password for $username" -AsSecureString


$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($webUrl) 
$ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($username, $password)
$web = $ctx.Web
$webs = $web.Webs
$lists = $web.Lists 

$ctx.Load($lists)
$ctx.Load($webs)
$ctx.Load($web)
$ctx.ExecuteQuery()

$lists| select -Property Title



Example:

#You need to run PowerShell in single-threaded mode (the authentication requires it).
powershell -STA
#Import the DLL.
[Reflection.Assembly]::LoadFile("{local path to the dll ClaimsAuth.dll}")
#Instantiate a new SPOContext providing your SharePoint Online site URL. (Don’t forget the https)
$ctx = new-object SPOContext("{Url of the site}")

#let's test it

$web = $ctx.Web
$lists = $web.Lists 

$ctx.Load($lists)
$ctx.Load($web)
$ctx.Load($web.Webs)
$ctx.ExecuteQuery()

$lists| Select -Property Title, ItemCount | FT -AutoSize

Now, it's finally is THE TIME, SharePoint Online Administators, to get know Client Side Object Model for SharePoint!