SharePoint Online: [Rest API & SharePoint App] How to access other web context

Required App permission to be setup in order to access the web, under AppManifest.xml

Example code snippet:

SP.AppContextSite is the core part to call from App to SharePoint


var hostweburl =
        decodeURIComponent(getQueryStringParameter("SPHostUrl"));

var appweburl =
        decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));

//Example: Get List Item
function getItems (listName, queryText, rowLimit) {
     var d = $.Deferred();
     var viewXml = '<View><Query>' + queryText + '</Query></View>';
     var query = {
         'query': {
            '__metadata': { 'type': 'SP.CamlQuery' },
            'ViewXml': viewXml
         }
     };
     //default limit
     var limit = 10;
     if (rowLimit)
        limit = rowLimit;
                
     var settings = {
        url: appweburl + "/_api/SP.AppContextSite(@target)/web/lists/GetByTitle('" + listName + "')/items?@target='" + hostweburl + "'&$top=" + limit,
        contentType: "application/json;odata=verbose",
        type: "GET",
        headers: {
            "accept": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val()
        },
        success: function (data) {                                                
           d.resolve(data.d.results);
        },
        error: function (data) {
            d.reject(data);
        }
      };

      if (queryText) {
        settings["data"] = JSON.stringify(query);
      }

      $.ajax(settings);

      return d.promise();
}

SharePoint Online: Page layouts operation with PnP PowerShell

First, you will have to connect to your SharePoint Online Site

Example: Connect to SPO

$siteurl = "https://yourspsite.sharepoint.com"  
Connect-SPOnline -Url $siteurl  
$ctx = Get-SPOContext  

Example: Adding Page Layout (e.g: Inherit from Article Page)

$ct = Get-SPOContentType -Identity "Article Page"
Add-SPOPublishingPageLayout -SourceFilePath "Path to your page layout aspx" `
                            -Title "Test layout" -Description "Test Page Layout" `
                            -AssociatedContentTypeID $ct.Id

Example: Retrieving Page Layout

Get-SPOListItem -List "Master Page Gallery" `
                -Query "<View><Query><Where><Contains><FieldRef Name='Title'/><Value Type='Text'>Test Layout</Value></Contains></Where></Query></View>"

Example: Deleting Page Layout

Will not be able to be deleted if any pages is using the page layout)

$layout = Get-SPOListItem -List "Master Page Gallery" `
                          -Query "<View><Query><Where><Contains><FieldRef Name='Title'/><Value Type='Text'>Test Layout</Value></Contains></Where></Query></View>"

Remove-SPOListItem -List "Master Page Gallery" -Identity $layout

SharePoint Online: Files operation with PnP Powershell

First, you will have to connect to your SharePoint Online Site

Example: Connect to SPO

$siteurl = "https://yourspsite.sharepoint.com"  
Connect-SPOnline -Url $siteurl  
$ctx = Get-SPOContext  

Example: How to retrieve/find files
*Site wide, not recommended

Find-SPOFile -Match *

From a list

Find-SPOFile -Match * -List "Documents"

From a site

$web = Get-SPOWeb -Identity "Subsite"
Find-SPOFile -Match * -Web $web

From a list in a site

$web = Get-SPOWeb -Identity "Subsite"
Find-SPOFile -Match * -Web $web -List "Pages"

Access file properties

$web = Get-SPOWeb -Identity "Subsite"
$files = Find-SPOFile -Match * -Web $web -List "Pages"
foreach($file in $files) {
     #get file properties
     $file.Title
     $file.Name
     $file.ServerRelativeUrl
     #etc...
}

Example: How to download file

Get-SPOFile -ServerRelativeUrl "Relative path to your file, e.g: /documents/testing.docx" `
            -Path "Local folder path, e.g: C:\temp" `
            -FileName "Download file name, e.g: test.docx"

Example: To check out the file

Set-SPOFileCheckedOut -Url "Relative path to your file, e.g: /documents/testing.docx"  

Example: To check-in the file

Set-SPOFileCheckedIn -Url "Relative path to your file, e.g: /documents/testing.docx" `
                     -CheckinType MajorCheckIn -Comment "Check"

Example: To add a single file

Add-SPOFile -Path "Path to source file" `
            -Folder "Path to destination folder" -Checkout

You can publish the file by adding -Publish, and publishing comments by adding -PublishingComment

Add-SPOFile -Path "Path to source file" `
            -Folder "Path to destination folder" `
            -Publish -PublishComment "Published by PnP script"

Example: To add a folder

Upload folder function

Function UploadFolder {
	Param(
	  [Parameter(Mandatory=$True)]
	  [String]$targetWeb,

	  [Parameter(Mandatory=$True)]
	  [String]$targetDir,

	  [Parameter(Mandatory=$True)]
	  [String]$path 

	)
	## get the full path to the source folder
	$fullPath = (Get-Item $path).FullName
	## recursively get all files in the directory
	$files = Get-ChildItem -Path $path -Recurse -File
	## upload each file to the directory specified before
	foreach($currentFile in $files)
	{
		## get relative path of documents
		$relativeDirectory = $currentFile.DirectoryName.Replace($fullPath, "").Replace("\","/")
		$uploadDirectory = $targetDir + $relativeDirectory
		Write-Host "Uploading" $currentFile.Name "to" $uploadDirectory "..." -ForegroundColor Yellow
		## Upload the document
		Add-SPOFile -Path $currentFile.FullName -Folder $uploadDirectory -Checkout
		Write-Host "Uploaded" $currentFile.Name "to" $uploadDirectory -ForegroundColor Green
	}
}

Example: How to use the function

UploadFolder -targetWeb "https://yourspsite.sharepoint.com/sites/test/" -targetDir "Style Library/folder" `
	     -path ("path to source folder in local drive")

 

SharePoint Online: Site Operation with PnP Powershell

First, you will have to connect to your SharePoint Online Site

Example: Connect to SPO

$siteurl = "https://yourspsite.sharepoint.com"  
Connect-SPOnline -Url $siteurl  
$ctx = Get-SPOContext  

Example: How to retrieve top level subsites

Get-SPOWeb -Identity "Subsite"

Example: Create a new subsite

$subsite = Get-SPOWeb -Identity "Subsite" -ErrorAction SilentlyContinue
if($subsite -eq $null) {
	Write-Host "Site does not exist, create..." -ForegroundColor Yellow
	#Create a Team Site STS#0
	#Create a Project Site PROJECTSITE#0
	#Create a Publishing Site CMSPUBLISHING#0
	#etc...
	New-SPOWeb -Title "Subsite" -Url "Subsite" -Template "STS#0" 
	Write-Host "Created site Subsite" -ForegroundColor Yellow		
}
else {
	Write-Host "Subsite already exist" -ForegroundColor Green
}

Getting subsites under the top level subsites

#assuming subsite exists
$subsite = Get-SPOWeb -Identity "Subsite"
$subsubsite =  Get-SPOSubWebs -Web $subsite | Where-Object -property Title -EQ -Value "subsubsite"

SharePoint Online: WebParts operation with PnP Powershell

First, you will have to connect to your SharePoint Online Site

Example: Connect to SPO

$siteurl = "https://yourspsite.sharepoint.com"  
Connect-SPOnline -Url $siteurl  
$ctx = Get-SPOContext  

==================== Accessing Web Parts on Page ====================

Retrieving a single web part

 
Get-SPOWebPart -ServerRelativePageUrl "Relateive Path to your page" -Identity "Web Part Identity"

Retrieving web part properties

 
$wp = Get-SPOWebPart -ServerRelativePageUrl "Relateive Path to your page" -Identity "Web Part Identity"

#Common Properties
$wp.Id
$wp.Title
$wp.ZoneId

#Other Properties
$wpProps = $wp.WebPart.Properties.FieldValues  
foreach($prop in $wpProps){  
    $prop ["XmlDefinition"]
}

Retrieving all web parts on a page

#this returns you the collection of web parts
$wps = Get-SPOWebPart -ServerRelativePageUrl "Relateive Path to your page"
#to loop through all the webparts
foreach($wp in $wps){  
     #Same as above to retrieve properties
     $wp.Id
     $wp.Title
     #etc...
}

==================== Adding Web Parts ====================

Add to Wiki Pages

Add-SPOWebPartToWikiPage -ServerRelativePageUrl "Relative Path to your page" `
                         -Path "Path to your .webpart/.dwp file" -Row 1 -Column 1 

Add to Publishing Pages

*You must check out the page before you can add any web parts

Add web part using webpart/DWP file

#check out the page for edit
Set-SPOFileCheckedOut -Url "Absolute Path to your page"

#adding webpart
Add-SPOWebPartToWebPartPage -ServerRelativePageUrl "Relative Path to your page" `
                            -Path "Path to your webpart/dwp file" `
                            -ZoneId "Header" -ZoneIndex 0

#check in the page
Set-SPOFileCheckedIn -Url "Absolute Path to your page" -CheckinType MajorCheckIn

Add web part using XML data

This options usually is useful when you are dealing with variable replacement

#check out the page for edit
Set-SPOFileCheckedOut -Url "Absolute Path to your page"

#retrieve xml from file
[string]$xml = (Get-Content "Source Path to your webpart file") `
               -replace "~variable~", "target value"

#adding webpart
Add-SPOWebPartToWebPartPage -ServerRelativePageUrl "Relative Path to your page" `
                            -xml $xml -ZoneId "Header" -ZoneIndex 0

#check in the page
Set-SPOFileCheckedIn -Url "Absolute Path to your page" -CheckinType MajorCheckIn

 

SharePoint Online: Page/List operation with PnP Powershell

First, you will have to connect to your SharePoint Online Site

Example: Connect to SPO

$siteurl = "https://yourspsite.sharepoint.com"  
Connect-SPOnline -Url $siteurl  
$ctx = Get-SPOContext  

Example: Retrieving page

$page = Get-SPOListItem -List "Pages" `
			-Query ("<View><Query><Where><Contains><FieldRef Name='Title'/><Value Type='Text'>" + $PageTitle + "</Value></Contains></Where></Query></View>") `
			-Web $Web
if($page -ne $null) {
	Write-Host "Page exists" -ForegroundColor Green
}
else {
	Write-Host "Page does not exist..." -ForegroundColor Red
}

Example: Retrieving all pages

$pages = Get-SPOListItem -List "Pages"  
foreach($page in $pages){  
    #Page Properties
    $page["Title"]  
    $page["FileRef"]
    #etc...
}  

Example: Adding a page

Add-SPOPublishingPage -PageName "testPage" ` 
                      -PageTemplateName "BlankWebPartPage" `
                      -Title "testPage" -Publish  

Example: How to update page properties

This can be also used to update the page layout of a publishing page


#Values type and reference from PnP site
#Single line of text: -Values @{"Title" = "Title New"}
#Multiple lines of text: -Values @{"MultiText" = "New text\n\nMore text"}
#Rich text: -Values @{"MultiText" = "New text"}
#Choice: -Values @{"Choice" = "Value 1"}
#Number: -Values @{"Number" = "10"}
#Currency: -Values @{"Number" = "10"}
#Currency: -Values @{"Currency" = "10"}
#Date and Time: -Values @{"DateAndTime" = "03/10/2015 14:16"}
#Lookup (id of lookup value): -Values @{"Lookup" = "2"}
#Yes/No: -Values @{"YesNo" = "No"}
#Person/Group (id of user/group in Site User Info List or email of the user, seperate multiple values with a comma): -Values @{"Person" = "user1@domain.com","21"}
#Hyperlink or Picture: -Values @{"Hyperlink" = "https://github.com/OfficeDev/, OfficePnp"}

#retrive the page
$PageTitle = "testPage"
$web = Get-SPOWeb -Identity "TestSubsite"
$page = Get-SPOListItem -List "Pages" `
			-Query ("<View><Query><Where><Contains><FieldRef Name='Title'/><Value Type='Text'>" + $PageTitle + "</Value></Contains></Where></Query></View>") `
			-Web $Web
#Update the page
Set-SPOListItem -List "Pages" -Web $web -Identity $page `
                -Values @{"Title"="Test Title"}

#Or alternatively if you know the page ID, e.g: 1
Set-SPOListItem -List "Pages" -Web $web ` 
                -Identity 1 -Values @{"Title"="Test Title"}

Example: Updating Publishing Page Layout

#retrieve page
$PageTitle = "testPage"
$web = Get-SPOWeb -Identity "TestSubsite"
$page = Get-SPOListItem -List "Pages" `
			-Query ("<View><Query><Where><Contains><FieldRef Name='Title'/><Value Type='Text'>" + $PageTitle + "</Value></Contains></Where></Query></View>") `
			-Web $Web

#check out the file for editing
Set-SPOFileCheckedOut -Web $Web -Url $page["FileRef"]

#updating properties
Set-SPOListItem -List "Pages" -Web $Web -Identity $page -Values @{"https://yourspsite.sharepoint.com/_catalogs/masterpage/BlankWebpartPage.aspx, Blank Web Part Page"}

#check in the update
Set-SPOFileCheckedIn -Web $Web -Url $page["FileRef"] -CheckinType MajorCheckIn -Comment "Checked in by script"   

Example: Deleting Page

$PageTitle = "testPage"
$web = Get-SPOWeb -Identity "TestSubsite"
$page = Get-SPOListItem -List "Pages" `
			-Query ("<View><Query><Where><Contains><FieldRef Name='Title'/><Value Type='Text'>" + $PageTitle + "</Value></Contains></Where></Query></View>") `
			-Web $Web
Remove-SPOListItem -List Pages -Identity $page -Web $web

SharePoint Online: Master Page Operation with PnP Powershell

First, you will have to connect to your SharePoint Online Site

Example: Connect to SPO

$siteurl = "https://yourspsite.sharepoint.com"  
Connect-SPOnline -Url $siteurl  
$ctx = Get-SPOContext  

Example: How to add master page

Add-SPOMasterPage -SourceFilePath "e.g: C:\temp\" -Title "master.aspx" `
                  -Description "Custom master page" `
                  -DestinationFolderHierarchy "Temp" -UiVersion 15

Example: Update master page settings

$MasterPageServerRelativeUrl = "/_catalogs/masterpage/Temp/master.aspx"
Set-SPOMasterPage -MasterPageServerRelativeUrl $MasterPageServerRelativeUrl `
                  -CustomMasterPageServerRelativeUrl $MasterPageServerRelativeUrl

Example: Update master page settings on subsites

$subWebs = Get-SPOSubWebs
$MasterPageServerRelativeUrl = "/_catalogs/masterpage/Temp/master.aspx"
foreach ($web in $subWebs) {
	Set-SPOMasterPage -MasterPageServerRelativeUrl $MasterPageServerRelativeUrl `
	                  -CustomMasterPageServerRelativeUrl $MasterPageServerRelativeUrl `
			  -Web $web.ServerRelativeUrl
}