Category Archives: PowerShell

Changing the default reply button in Outlook Web Access from “Reply all”

Your users may have noticed that the default reply button in Outlook Web Access is “Reply all”. This can result in emails accidentally being sent to the wrong person (as many users assume this is the reply button without reading it).

Reply all in OWA is default

Luckily you can change this default behaviour.

Change for an individual user

The user can change this setting themselves by going into the Mail settings.

Mail Settings

Under Mail, Automatic processing and Reply settings, the user can change the default response to “Reply”.

Reply settings

Change for all users

There is a PowerShell command which will set this for a mailbox.

Set-MailboxMessageConfiguration cloudacademy -IsReplyAllTheDefaultResponse $false

We can take this further and loop through all the mailboxes to apply this setting.

Get-Mailbox -ResultSize unlimited -Filter {(RecipientTypeDetails -eq 'UserMailbox')} | Set-MailboxMessageConfiguration -IsReplyAllTheDefaultResponse $false

Changed to reply

Hopefully you have happy users again after that change! Video guide below.



Using PowerShell to add a list or library WebPart to a SharePoint publishing page via CSOM

Thought I would share this as I struggled to find a complete article online how to do this. First of all, the code below is based on José Quinto’s post USING POWERSHELL TO ADD WEBPART TO SHAREPOINT PAGE VIA CSOM IN OFFICE 365. It’s a really good article on adding a content editor web part to a publishing page.

I couldn’t find any posts online on how to use the same technique to add a list view web part to a page. Eventually I figured out how to create the XML for adding a list view web part.

This is an adaptation of Jose’s function to add a web part to a page:

function AddWebPartToPage ($ctx, $sitesURL, $WebPartXml, $pageRelativeUrl, $wpZoneID, $wpZoneOrder) {
	try{
		Write-Host "Starting the Process to add the User WebPart to the Home Page" -ForegroundColor Yellow
		#Adding the reference to the client libraries. Here I'm executing this for a SharePoint Server (and I'm referencing it from the SharePoint ISAPI directory, 
		#but we could execute it from wherever we want, only need to copy the dlls and reference the path from here        
		Add-Type -Path "c:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.dll" 
		Add-Type -Path "c:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Runtime.dll" 
		Write-Host "Getting the page with the webpart we are going to modify" -ForegroundColor Green
		#Using the params, build the page url
		$pageUrl = $sitesURL + $pageRelativeUrl
		Write-Host "Getting the page with the webpart we are going to modify: " $pageUrl -ForegroundColor Green
		#Getting the page using the GetFileByServerRelativeURL and do the Checkout
		#After that, we need to call the executeQuery to do the actions in the site
		$page = $ctx.Web.GetFileByServerRelativeUrl($pageUrl);
		$page.CheckOut()
		$ctx.ExecuteQuery()
		try{
		#Get the webpart manager from the page, to handle the webparts
		Write-Host "The page is checkout" -ForegroundColor Green
		$webpartManager = $page.GetLimitedWebPartManager([Microsoft.Sharepoint.Client.WebParts.PersonalizationScope]::Shared);
		Write-Host $WebPartXml.OuterXml
		#Load and execute the query to get the data in the webparts
		Write-Host "Getting the webparts from the page" -ForegroundColor Green
		$ctx.Load($webpartManager);
		$ctx.ExecuteQuery();
		#Import the webpart
		$wp = $webpartManager.ImportWebPart($WebPartXml.OuterXml)
		#Add the webpart to the page
		Write-Host "Add the webpart to the Page" -ForegroundColor Green
		$webPartToAdd = $webpartManager.AddWebPart($wp.WebPart, $wpZoneID, $wpZoneOrder)
		$ctx.Load($webPartToAdd);
		$ctx.ExecuteQuery()
		}
		catch{
			Write-Host "Errors found:`n$_" -ForegroundColor Red
		}
		finally{
			#CheckIn and Publish the Page
			Write-Host "Checkin and Publish the Page" -ForegroundColor Green
			$page.CheckIn("Add the User Profile WebPart", [Microsoft.SharePoint.Client.CheckinType]::MajorCheckIn)
			$page.Publish("Add the User Profile WebPart")
			$ctx.ExecuteQuery()
			Write-Host "The webpart has been added" -ForegroundColor Yellow 
		}	
	}
	catch{
		Write-Host "Errors found:`n$_" -ForegroundColor Red
	}
}

And this is the XML to add a SharePoint document library called “Documents” to the page.

$WebPartXml1 =  "
		<webParts>
			<webPart xmlns='http://schemas.microsoft.com/WebPart/v3'>
				<metaData>
				<type name='Microsoft.SharePoint.WebPartPages.XsltListViewWebPart, Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c' />
				<importErrorMessage>Cannot import this Web Part.</importErrorMessage>
			</metaData>
			<data>
				<properties>
					<property name='ListUrl' type='string'>Documents</property>
					<property name='ListName' type='string'>Documents</property>
				</properties>
			</data>
			</webPart>
		</webParts>"

The URL for a list is slightly different to a document library, the example below is the XML for an announcement list.

$WebPartXml1 =  "
		<webParts>
			<webPart xmlns='http://schemas.microsoft.com/WebPart/v3'>
				<metaData>
					<type name='Microsoft.SharePoint.WebPartPages.XsltListViewWebPart, Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c' />
					<importErrorMessage>Cannot import this Web Part.</importErrorMessage>
				</metaData>
				<data>
					<properties>
						<property name='ListUrl' type='string'>Lists/Student Announcements</property>
						<property name='ListName' type='string'>Student Announcements</property>
						<property name='JSLink' type='string'>~sitecollection/Style%20Library/cdb_custom_announcements/cdb_custom_announcements.js</property>
					</properties>
				</data>
			</webPart>
		</webParts>"

I then get the client context and pass the XML and variables to the function to add it to the page

$tenantAdmin = "user@domain.com"
$tenantAdminPassword = "password"
$secureAdminPassword = $(convertto-securestring $tenantAdminPassword -asplaintext -force)
$siteURL = "https://domain.com/sites/subsite";
$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl) 
$credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($tenantAdmin, $secureAdminPassword)  
$ctx.Credentials = $credentials
$relUrl = "/sites/subsite"
$pageRelativeUrl1 = "/Pages/Default.aspx"
$wpZoneID1 = "Top Left"
$wpZoneOrder1 = 0
#Run function
AddWebPartToPage $ctx $relUrl $WebPartXml1 $pageRelativeUrl1 $wpZoneID1 $wpZoneOrder1

Nice example of adding web parts to a SharePoint Online publishing page using PowerShell CSOM.

Adding SharePoint Online navigation from XML using PowerShell CSOM

The following PowerShell scripts were created to enable me to deploy a custom navigation across multiple site collections. You can use managed metadata navigation as mentioned in my previous post. Unfortunately this method doesn’t allow the user to reuse managed metadata navigation across multiple site collections (no idea why, I thought that was one of the advantages of managed metadata navigation!).

So a new and clean way of doing this is to use the CSOM for PowerShell. The code below deletes every navigation node using the first function and then adds each item added to an XML file. A strength of using this method is it can be manipulated to add additional logic for adding links to particular site collections depending on the variables in the XML file. Hope you find this useful.

For SharePoint design, workflows, automation, training and support please visit my SharePoint consultancy site www.clouddesignbox.co.uk. We offer education and business SharePoint solutions and services.

Deleting all navigation nodes using CSOM PowerShell

It’s fairly straightforward to enumerate nodes in an array, in this example I’m deleting all the top navigation menu nodes in a SharePoint site. This is how I would normally loop through the top navigation menu:

$topNav = $context.Web.Navigation.TopNavigationBar;
$context.Load($topNav);
foreach ($topNavItem in $topNav)
{
	Write-Host $topNavItem.Title
}

However if I want to loop through the menu and delete all the nodes, the above function errors as the array has changed each time it loops, the method below works but doesn’t catch all the menu items.

for ($ii = 0; $ii -lt $topNodes.Count; $ii++)
{
	Write-Host $topNodes[$ii].Title 
	$topNodes[$ii].deleteObject();
	$context.ExecuteQuery();
}

As we are enumerating the nodes, we are removing nodes from the start and changing the position of the other nodes in the array. As the loop continues to run, it can skip positions of some of the nodes.

A solution which works better is looping through the array backwards. As you loop through the array backwards, it doesn’t change the position of items still in the array.

for ($ii = $topNodes.Count - 1; $ii -ge 0; $ii--)
{
	Write-Host $topNodes[$ii].Title 
	$topNodes[$ii].deleteObject();
	$context.ExecuteQuery();
}

Hope you may find this useful, it can be difficult to find why the loop misses some random items and hopefully looping backwards will avoid any issues like this.

How to stop using custom master pages when branding SharePoint



With the rise of Office 365 and SharePoint online, the ancient practice of using a custom master page to brand a SharePoint site is coming to an end. SharePoint online has many incremental changes, bug fixes and improvements to the Seattle master page meaning that if you have taken a copy of this Master Page to apply your branding, you could be missing out on the constant evolution of SharePoint online.

Custom Master Pages can still be used but Microsoft recommend against this now. The good news is that we can make exactly the same branding changes without having to use a custom master page.

I will briefly mention that you can create themes for SharePoint very quickly using Microsoft’s free tool which can be downloaded from here. Great for quick colour palettes and background images but not great if you want a responsive or more custom design.

Custom master pages (for branding purposes) tended to have a small number of adjustments such as:

  • Custom HTML (maybe for a menu container)
  • Links to CSS files (for responsive styling and branding)
  • Links to JavaScript files (for use of jQuery and additional libraries)

Link to custom CSS file

A link to a custom CSS file is recommended for advanced branding changes. This won’t affect any improvements to the default Seattle master page however you may need to update the CSS from time to time to reflect any interface changes. The alternative CSS link can be set via the GUI on a publishing site or by CSOM on any site.

As a designer, you will be aware that you can’t do everything in CSS such as placeholders for menus or other interactive content or run JavaScript.

Inject JavaScript

JavaScript and HTML plays a big role in most branding exercises. It could be DOM manipulation, a responsive menu, sliding effects or responsive background slideshows and JavaScript tends to be a requirement on most projects. Luckily there is some more good news, JavaScript can be added to a site without editing the Master Page by adding custom actions.

You should already be storing JavaScript in external files (in the Style Library) rather than embedding on the master page. So the only change is to inject these JavaScript files rather than reference them on the MasterPage. This can be done via CSOM (I use the PowerShell method).

#Run all of your lines to load the context of the site collection
$context.Load($site)

#add custom js injection action
$customJSAction = $site.UsercustomJSActions.Add();
$customJSAction.Location = “ScriptLink”;
#reference to JS file
$customJSAction.ScriptSrc = “~SiteCollection/Style Library/JS Display Templates/test.js”;
#load it last
$customJSAction.Sequence = 1000;
#make the changes
$customJSAction.Update();
$context.ExecuteQuery();

You can use the same objects to remove all the custom actions and list them. You can find out more information and the C# examples here.

Conclusion

Although this is a different way of thinking about branding, in the long run, it’s cleaner and more reusable than custom master pages. Your customers will have a better experience in Office 365 but even CSS and DOM manipulation may need updating as SharePoint evolves.

Some really useful examples and more detailed explanations can be found on Vesa Juvonen’s Ignite talk. In Vesa’s example he uses Visual Studio and Apps to deploy the CSS and JS.

In the video at the top of the post, I quickly go through the process of setting alternative CSS and JavaScript custom actions.

Setting up Azure Connect (DirSync) for Office 365

I’ve made a quick video guide on how to set-up Azure Connect (DirSync) to sync with Office 365. It’s done using a simple demo environment and I suspect that you may find complications and other errors when trying this out in a production live environment. Hopefully this is of use to you (even if it just makes it seem less scary!). I will try to get chance to write up this blog post in more detail rather than just the video at some point in the future.



Using PowerShell to find last DirSync

When troubleshooting DirSync issues with Office 365, it is sometimes difficult to know if the DirSync successfully applied to Office 365.

There is a quick way to check this and it provides the data for when the update last took place. First you will need to make sure that you have installed the Azure AD Module for PowerShell, you can download from here.

When this has installed, run Connect-MsolService to connect to the Office 365 tenancy, this should be a global administrator account.

Azure Connect PowerShell

Then run Get-MsolCompanyInformation to get the tenancy information which includes the last dirsync time and last password sync



Looping through all subsites in SharePoint Online

SharePoint Online requires use of the Client Object model when modifying the site via PowerShell due to there being no backend server exposed in Office 365. Users with previous experience of using JavaScript Client Object model will find this a familiar method.

In the example below, the Powershell iterates through all subsites (and subsites of subsites) in a site collection or root site. This could be used for disabling a web scoped feature or automating site modification.

First of all, the variables are initiated including the path to the relevant DLLs.

#connection variables and reference DLL
$username = "user@onmicrosoft.com"
$password = "Password123"
$SiteCollectionUrl = "https://tonyishere.sharepoint.com"
Add-Type -Path "c:\Microsoft.SharePoint.Client.dll"

A new object for the client context requires creating, this can be done in a reusable function as shown below.

# Generate ClientContext function so we can reuse
function GetClientContext($SiteCollectionUrl, $username, $password) {
     $securePassword = ConvertTo-SecureString $password -AsPlainText -Force
     $context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteCollectionUrl) 
     $credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($username, $securePassword) 
     $context.Credentials = $credentials
     return $context
}

The following function has a nested call to call itself, this enables it to iterate through subsites of subsites. Without the nested function call, it would only cover a single subsite depth. The function writes the url of the site to the screen but this could be replaced with more complex functionality such as enabling a feature or creating a list item.

# function to loop through subsites
function catchsubsites ($subsiteurl){
	$clientContext = GetClientContext $subsiteurl $username $password
	$rootWeb = $clientContext.Web
	$childWebs = $rootWeb.Webs
	$clientContext.Load($rootWeb)
	$clientContext.Load($childWebs)
	$clientContext.ExecuteQuery()
	#do something on top level site
	write-host $rootWeb.url -ForegroundColor Yellow
	foreach ($childWeb in $childWebs)
	{
		#do something for each subsite
		write-host $childWeb.url -ForegroundColor Yellow
		#see if there are any subsites beneath this and loop all of them too
		catchsubsites $childWeb.url
	}
}

Finally the function is called to kick off the whole process of looping through the site.

#Finally run the function to get it all started!
catchsubsites $SiteCollectionUrl

This example could be refined so that it doesn’t authenticate at every request but it does show how simple it can be to create the complex PowerShell scripts that we are all used to using on SharePoint on-premises in the cloud version of Microsoft’s Office 365 SharePoint Online.

Update: Code updated 01/10/2016, fixed variable in loop and added section to run code for parent site