Hi All,

Next step towards Office 365 development is uploading /adding a web part page in “SitePages” library of team site. The site is not publishing site so we couldn’t like upload the empty page and then apply PageLayout.

So we will require a local copy of page having appropriate zones. Example of page (default.aspx) structure (this page is just for reference):



Following are the steps and script:

  1. Get the Microsoft.SharePoint.Client.ClientContext instance
  2. Get the Web instance
  3. Get the “Site Pages” library
  4. Get the root folder and files collection
  5. For adding file, we need to create instance of Microsoft.SharePoint.Client.FileCreationInformation. Set the properties of this instance like FileUrl, FileContent etc.
  6. Use the Add () method of files collection.

Script

  1. #Variables which we are used below
  2. $url = http://MyWeb.com
  3. $LayoutPath = “c:\default.aspx”
  4. $PagesLibraryTitle = “Site Pages”
  5. $FileNameWithExtention = “default.aspx”
  6. # All the above variables can be parameterised
  7. #Password to connect the Office 365 site
  8. $securePassword = ConvertTo-SecureString -String $Password -AsPlainText –Force
  9. #instance of Client Context
  10. [Microsoft.SharePoint.Client.ClientContext]$clientContext = New-Object Microsoft.SharePoint.Client.ClientContext($url)
  11. $clientContext.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName, $securePassword)
  12. #here assuming we are adding file to root web of site collection
  13. $site = $clientContext.Site
  14. $web = $site.RootWeb
  15. $clientContext.Load($web)
  16. $clientContext.ExecuteQuery()
  17. #List Collection
  18. $lists = $web.Lists
  19. $clientContext.Load($lists)
  20. $clientContext.ExecuteQuery()
  21. #Get the list
  22. $list = $lists.GetByTitle($PagesLibraryTitle)
  23. $clientContext.Load($list)
  24. $clientContext.ExecuteQuery()
  25. #Files Collection
  26. $files = $list.RootFolder.Files
  27. $clientContext.Load($files)
  28. $clientContext.ExecuteQuery()
  29. #instance of FileCreationInformation
  30. [Microsoft.SharePoint.Client.FileCreationInformation]$fileCreationInfo = New-Object Microsoft.SharePoint.Client.FileCreationInformation
  31. #Get the file content
  32. $fileContent = Get-Content $LayoutPath
  33. #convert the file content into Byte[] and set it to Content property of FileCreationInfo class
  34. $fileCreationInfo.Content = [System.Text.Encoding]::UTF8.GetBytes($fileContent)
  35. $fileCreationInfo.Url = $FileNameWithExtention #(default.aspx)
  36. #add the file
  37. $page = $files.Add($fileCreationInfo)
  38. $clientContext.ExecuteQuery()
Thanks

Feel free to comment / feedback / suggestions / thoughts if any or if you have any query