Sharing a File in SharePoint Online or OneDrive with PowerShell

I have been diving into doing larger scale operations in SharePoint Online using the Client Side Object Model (CSOM) utilizing PowerShell and ran into a scenario that I couldn’t easily find documented anywhere. What I wanted to do was technically “share” a file with a specific user and have that user receive an email just like if it was done through the GUI. What I didn’t want to see is just the breaking of permissions. What I found was the Web.ShareObject method and this great blog post from Vesa Juvonen in 2015

Once I found this I started working on putting this into a useful PowerShell format. To get started with CSOM & PowerShell with SharePoint Online here is a good blog post from Chris O’Brien. You can get the latest version of SharePoint Online CSOM here. If you download the nuget file you can change the file extension to .zip and extract the .dlls.

Here is link to the GitHub rep and I will break it down below along with the script. Here are some key things to note:

  • The Web.ShareObject method has been updated since the Vesa blog post with a parameter called useSimplifiedRoles that can be used for utilizing modern sharing
  • SharePoint PnP has extended the sharing APIs and built a sample that can be used
  • This script is built to share a file based on filename within a site to a single user
  • This works on SharePoint Online and OneDrive for Business
  • It will share as the user who runs the script
  • This script could be updated to share a site or to multiple people
  • You can share with Edit or View permission based on the roleValue
  • It doesn’t replicate the modern sharing UI in capabilities exactly (more of what occurs details below)

To utilize the script make sure you fill out the appropriate variables and more information about what this will do is below the script. 

# Use this script to share a file via CSOM and PowerShell
# ShareObject https://msdn.microsoft.com/en-us/library/office/mt684216.aspx
# External sharing blog https://blogs.msdn.microsoft.com/vesku/2015/10/02/external-sharing-api-for-sharepoint-and-onedrive-for-business/

### ENTER YOU VARIABLES HERE ###

#path to the SP CSOM files 
$csomPath = "C:\...." 

#Email of person running the script
$adminEmail = "user@domain.com"

#Site collection to be connected to
$siteUrl = "https://site.sharepoint.com/sites/site"

#Library title where the file exists
$libraryTitle = "Documents" 

#Filename including file type
$fileName = "Test Document 1.docx"

#Email of who the document is being shared to
$emailSharedTo = "user2@domain.com"

#UNVALIDATED_EMAIL_ADDRESS if they are in AD or GUEST_USER if they are not
$principalType = "UNVALIDATED_EMAIL_ADDRESS"  

#role:1073741826 = View, role:1073741827 = Edit
$roleValue = "role:1073741827"

#A flag to determine if permissions should be pushed to items with unique permissions.
$propageAcl = $true

#Flag to determine if an e-mail notification should to sent, if e-mail is configured.
$sendEmail = $true  

#If an e-mail is being sent, this determines if an anonymous link should be added to the message.
$includedAnonymousLinkInEmail = $false  

#The ID of the group to be added to. Use zero if not adding to a permissions group. Not actually used by the code even when user is added to existing group. 
$groupId = 0

#Doesn't matter as it isn't sent in current email format
$emailSubject = ""

#Text for the body of the e-mail.
$emailBody = "Check out my email body"  

#Use modern sharing links instead of directly granting access
$useSimplifiedRoles = $true
################

# Get CSOM files
Add-type -Path "$csomPath\Microsoft.SharePoint.Client.dll"
Add-type -Path "$csomPath\Microsoft.SharePoint.Client.Runtime.dll"

# Connnect to site
$ss = Read-Host -Prompt "Enter admin password" -AsSecureString
$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl)
$creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($adminEmail, $ss)
$ctx.Credentials = $creds
if(!$ctx.ServerObjectIsNull.Value) { 
    Write-Host "Connected to site:" $siteUrl -ForegroundColor Green 
} 
# Get web
$web = $ctx.Web

# Connect to library
$list = $web.Lists.GetByTitle($libraryTitle)
$ctx.Load($web)
$ctx.Load($list)
$ctx.Load($list.RootFolder)
$ctx.ExecuteQuery()

# Get doc
$query = New-Object Microsoft.SharePoint.Client.CamlQuery
$caml ="<View Scope='RecursiveAll'><Query><Where><Eq><FieldRef Name='FileLeafRef'/><Value Type='File'>" + $fileName + "</Value></Eq></Where></Query></View>"
$query.ViewXml = $caml
$item = $list.GetItems($query)
$ctx.Load($item)
$ctx.ExecuteQuery()
if (!$item) {
    Write-Host "Could not find the file:" $fileName -ForegroundColor Yellow 
} else {
    Write-Host "Sharing the the file:" $item.FieldValues.FileLeafRef -ForegroundColor Green 
}

# Get doc url
$itemUrl = $item.FieldValues.FileRef
$split = $web.Url -split '/'
$itemUrl = "https://" + $split[2] + $itemUrl

# Build user object to be shared to
$jsonPerson = "[{`"Key`":`"$emailSharedTo`",
`"Description`":`"$emailSharedTo`",
`"DisplayText`":`"$emailSharedTo`",
`"EntityType`":`"`",
`"ProviderDisplayName`":`"`",
`"ProviderName`":`"`",
`"IsResolved`":true,
`"EntityData`":{`"Email`":`"$emailSharedTo`",
    `"AccountName`":`"$emailSharedTo`",
    `"Title`":`"$emailSharedTo`",
    `"PrincipalType`":`"$principalType`"},
`"MultipleMatches`":[]}]"

# Initiate share
$result = [Microsoft.SharePoint.Client.Web]::ShareObject($web.Context,$itemUrl,$jsonPerson,$roleValue,$groupid,$propageAcl,$sendEmail,$includedAnonymousLinkInEmail,$emailSubject,$emailBody,$useSimplifiedRoles)
$web.Context.Load($result)
$web.Context.ExecuteQuery()

Write-Host "Status of the share:" $result.StatusCode -ForegroundColor Green

Starting from a non shared file this is what you will see based on different configurations:

Sharing with useSimplifiedRoles set to $true and sendEmail set to $true

  • The file does not have inheritance broken

  • After initiating the ShareObject, inheritance is broken but you don’t see any changes

  • The person being shared to receives an email that the person who ran the script wants to share a file with you and you will see the email subject is preset but the email body is included

  • Once the person being shared to clicks on the link you can see a new ‘Managed Links’ section in the item permissions

  • If you follow that link you will see the item is now shared with that individual

Sharing with useSimplifiedRoles set to $true and sendEmail set to $false

  • The file does not have inheritance broken
  • After initiating the ShareObject, inheritance is broken but you don’t see any changes if the user tries to access the file through the document library
  • There is a new link viewable in the modern manage access section showing a new sharing link and that someone can access via that link

  • If the user accesses the file via that link you can see a new ‘Managed Links’ section in the item permissions and you can see that user in the Shared with section

 

Sharing with useSimplifiedRoles set to $false and sendEmail set to $false

  • The file does not have inheritance broken
  • After initiating the ShareObject, inheritance is broken but you don’t see any changes even after a user accesses the file, that means this does nothing but break inheritance

Sharing with useSimplifiedRoles set to $false and sendEmail set to $true

  • The file does not have inheritance broken
  • After initiating the ShareObject, inheritance is broken but you don’t see any changes
  • Once a user accesses the file via the link in the email they are granted permissions directly to the file (contribute instead of edit)

Ending…

After putting this together I realized I don’t really have a great use case to actually use this. Either way it was a good learning experience for me as I am just getting started into this kind of CSOM & PowerShell work and maybe it will come in handy for someone else in the future. 

Office 365 Groups Naming Policy

group1

Introduction

When Office 365 Groups were first released there was not an ability to control the names of Groups at all. One of the primary reasons for this was due to the cross workload functionality that make up Office 365 Groups. As a reminder, an Office 365 Group is the single Azure AD identity service that provides specific membership to Office 365 solutions like SharePoint, Exchange, Planner, Teams, etc. Within each of these workloads you have the ability to create and manage an Office 365 Group. If you make a change within one of workloads, for example SharePoint, there is communication between the workload and Azure AD with notifications on things like creation, changes, and deletions. 

With a separated system and Azure AD as the source, any policies need to be applied at the Azure AD level. As an example, an Exchange naming policy can be used (and at one point was the only option) for Office 365 Groups. If you set a naming policy within Exchange that would only work if you tried creating a group within Exchange. If I was on SharePoint Home and tried to create an Office 365 Group that naming policy would not trigger as I technically not working in Exchange. Exchange would learn about the Group after it is synced back to Azure AD but that would be too late. 

To resolve this issue Microsoft has released Office 365 Group naming policy capabilities at the Azure AD level. A naming policy is very important for proper control and a clean Global Address List (GAL). Since this is in Azure AD now the naming policy is applied to Groups that are created across workloads. 

Details

As I am writing this post in Dec 2017 this is currently still in Private Preview. 

Both of these currently can only be configured with PowerShell. The prerequisites for configuring these can be found in this post: Managing Office 365 Groups using Azure AD PowerShell V2.

The AzureADPreview PowerShell module version 2.0.0.137 is required.

Office 365 Group naming policies can be built using 2 different features and 1 is automatically maintained:

  • Custom blocked words
    • You can set specific blocked words that can be used within Group names. 
  • Prefix-Suffix naming policy
    • Using fixed strings or user attributes, you can add an automated prefix or suffix to a Group name. 
  • Microsoft Standard blocked words list
    • A set of words Microsoft manages that are not allowed. This includes your primary swear words. I tested quite a few good ones and they were all blocked automatically.

These administrators bypass or are exempt from the naming polices you configure but NOT the MS standard blocked words list:

  • Global Administrator
  • Partner Tier 1 Support
  • Partner Tier 2 Support
  • User Account Administrator
  • Directory Writers

Microsoft detailed information for the naming policy can be found here.


Custom blocked words

This is a comma separated list of words that you can configure. These words are blocked in Group names and aliases. Some examples of when you would want to configure blocked words:

  • Your department or business function names because you want to ensure you don’t have duplicate places for content
  • Regulatory words that you may have specific legal requirements around that you need to have more control over
  • Names of roles that you don’t want people to try to impersonate
  • Client, Vendor, or Competitor names

There are some things to know about these blocked words.

  • The checks are done AFTER appending the prefix/suffix to the Group name
    • If things like underscores (_) or dashes (-) are used in prefix/suffix they could stop your blocked word from working if there are no spaces
  • No sub-string searches are done
    • If “Drew” is the blocked word, “Andrew” would still work
  • Not case-sensitive
  • No character restrictions
  • No limit on the amount of words

Steps to set the Custom Blocked words

This is assuming you already have a directory settings template created, details in prior post, and connection information from the first section.

1 – Connect to Azure AD via PowerShell.

Connect-AzureAD

2 – Use comma delimited values for the blocked words.

$settings = Get-AzureADDirectorySetting | where-object {$_.displayname -eq “Group.Unified”}
$settings["CustomBlockedWordsList"] = "HR,Contoso,Payroll,CEO,CFO,CIO"
Set-AzureADDirectorySetting -Id $settings.Id -DirectorySetting $settings

3 – Review your updated settings; you can now see the default values for the directory settings object.

Get-AzureADDirectorySetting | ForEach Values


Prefix-Suffix naming policy

These can either be fixed strings or actually attributes from the user themselves. These 2 types of capabilities are stored within 1 overall string that is concatenated. Because of this, you must always have [GroupName] included in your setting. That is how you are able to have a prefix & a suffix. 

Some examples of using strings:

  • GRP [GroupName]
    • This puts the fixed string of “GRP ” before all of your Group names
  • #[GroupName] Group
    • This will put the # symbol at the front of the Group name for better sorting in the GAL and then ” Group” as a suffix for better clarity
    • Special characters are removed from the Alias
  • OGRP – [GroupName]
    • Dashes can be used for separation as spaces are removed automatically in the Group Alias (like the rest of the special characters). That means “OGRP – Drew” as a group name becomes “OGRP-Drew@domain.com” as the alias instead of “OGRPDrew@domain.com”.

The next type of thing you can add are Azure AD user attributes. The following attributes are supported: [Department], [Company], [Office], [StateOrProvince], [CountryOrRegion], [Title], [CountryCode]

Some examples of using attributes:

  • [Department] – [GroupName]
    • This will pull the users department stored in Azure AD before the Group name
  • [CountryCode] – GRP – [GroupName]
    • This will first put the Country Code stored in Azure AD followed by a fixed string and then the Group name

There are some things to know about using attributes.

  • The total prefix/suffix + string length is restricted to 53 characters
  • Empty attributes for users will be filled in with blank values. It is best to ensure your Azure AD information is fully established before using these attributes.
  • Extension attributes and custom attributes are not supported
    • If you put it in an unsupported attribute it just comes across as text

Steps to set the Prefix – Suffix naming policy

This is assuming you already have a directory settings template created, details in prior post.

1 – Use comma delimited values for the blocked words.

$settings = Get-AzureADDirectorySetting | where-object {$_.displayname -eq “Group.Unified”}
$settings["PrefixSuffixNamingRequirement"] = "GRP - [Department] - [GroupName]"
Set-AzureADDirectorySetting -Id $settings.Id -DirectorySetting $settings

2 – Review your updated settings; you can now see the default values for the directory settings object.

Get-AzureADDirectorySetting | ForEach Values


Microsoft standard blocked words

There are a lot of unprofessional words naturally in the English language that most likely should never be part of an Office 365 Group name. This includes a primary set of things like swear words and other inappropriate words that your imagination may be able to come up with. This is a single setting to turn on the blocked words or off. 

Steps to set the Microsoft blocked words

This is assuming you already have a directory settings template created, details in prior post, and connection information from the first section.

1 – Use comma delimited values for the blocked words.

$settings = Get-AzureADDirectorySetting | where-object {$_.displayname -eq “Group.Unified”}
$settings["EnableMSStandardBlockedWords"] = $true
Set-AzureADDirectorySetting -Id $settings.Id -DirectorySetting $settings

2 – Review your updated settings; you can now see the default values for the directory settings object.

Get-AzureADDirectorySetting | ForEach Values


And when you put it all together!

You get a blocked word of CEO and a naming policy pulling in a prefix of “GRP – ” with an Azure AD department of “NFL” and a suffix of ” – CEO”. You will also see the alias removing the spaces.


Where does the naming policy actually work?

As there are a lot of workloads across Office 365 that utilize Groups there are a lot of places that these policies need to work. Currently it is not supported in every workload. Microsoft has the detailed information for what is supported in their support article here

Here is the current breakdown in Dec 2017.

Where it works:

  • Outlook on the Web
  • Outlook Client – Doesn’t preview
  • Outlook Mobile – Doesn’t preview
  • Teams
  • SharePoint
  • Stream
  • Groups mobile app
  • Planner
  • Dynamics 365
  • Exchange PowerShell
  • Azure AD PowerShell
  • O365 Admin Center

Where it doesn’t:

  • Power BI workspace
  • Yammer
  • StaffHub
  • Azure AD Portal

Licensing

Any Office 365 subscription that has Exchange Online and SharePoint Online will support groups. That includes the Business Essentials and Business Premium plans, and the Enterprise E1, E3 and E5 plans.

There is a large collection of features that require specific types of Azure AD licenses. The Office 365 Groups naming policy requires Azure AD Premium P1 licenses for any users who are part of Office 365 Groups.

The full collection of licensing information is listed from Microsoft here.

Speaking about OneDrive at the Collab365 Global Conference

Have you heard about the virtual Collab365 Global Conference 2017 that’s streaming online November 1st – 2nd?

Join me and 120 other speakers from around the world who will be bringing you the very latest content around SharePoint, Office 365, Flow, PowerApps, Azure, OneDrive for Business and of course the increasingly popular Microsoft Teams. The event is produced by the Collab365 Community and is entirely free to attend.

Places are limited to 5000 so be quick and register now.

During the conference I’d love you to watch my session which is called : ‘What’s New with OneDrive for Business’

Have you seen all the new features in OneDrive for Business (OD4B) lately? Are you getting ready to roll-out OD4B to your enterprise? Or are you just looking to see what you’re missing if you aren’t on OD4B yet? OneDrive for Business in Office 365 is changing quickly and we as end-users and IT professionals need to try keep up. Join me as we walk through the newest improvements to the world of OneDrive for Business in Office 365. This session will be demo filled and by the end you will see the investment and dedication that Microsoft has too provide a solid personal file solution.​

If you join me, you will learn:

  • New features in OD4B.
  • What’s coming next in OD4B?
  • What does the current experience look like?

Topic(s):

  • OneDrive

Audience :

  • End User
  • IT Architect

Time (in UTC) :

  • Thursday, November 2 2017 12:00 AM

How to attend :

  1. Register here.
  2. At the time listed above go here to watch my session. (you can also add me to your own personal planner from the agenda.
  3. Be ready to take notes!

SharePoint, OneDrive & Office 365 Collaboration Announcements from Ignite 2017

I will be keeping track of all of the announcements that I can keep up with around SharePoint, OneDrive, and the Office 365 collaboration space at Microsoft Ignite next week using Sway. Since I am using Sway you will be seeing my updates live as I type and publish them.  That means this will be an evergreen Sway and hopefully a 1 stop shop for anyone looking to catch up on all the great news coming out of Ignite. 

 

Speaking at Microsoft Ignite

One of the biggest Microsoft events is just around the corner down in Orlando, Florida. Microsoft Ignite is the conglomerate of smaller technology specific events like the SharePoint Conference and TechEd. It is the yearly gathering for IT professionals and really anyone working with Microsoft to learn about the new modern solutions that are being released and what is next. It also is one of the best times to network and consult with other experts from around the world. Hopefully through keynote, breakout, and community sessions you will learn where you should be concentrating your learning efforts moving forward. 

Personally I have been lucky to attend both of previous Microsoft Ignites (2015 & 2016) along with previous Microsoft SharePoint Conferences. This year I am honored to be selected to speak at Ignite 2017.  This will be my first time speaking at either Ignite or a previous SPC. 

My session info & link:

  • Title: Can I get a side of OneDrive for Business with my SharePoint?
  • Description: When working with Microsoft collaboration tools there is always a lot of conversation about what to use when. SharePoint and OneDrive for Business are best served together in Office 365. In this session, we walk through OneDrive for Business and the capabilities for collaboration and how they relate to your overall SharePoint solution.
  • Date: Tuesday, September 26th at 5:05 p.m. 
  • Location: OCCC South – Expo Theater #1
  • Link to files & conversation in Tech Community

I am hoping during my session I can speak to a lot of the great things that Microsoft already has out there in the OneDrive & SharePoint space and real-world scenarios of how they are best used together.   I work with a lot of clients in Office 365 across a lot of industries and of all sizes.  I have seen a lot of successful Office 365 collaboration implementations and some that I know could be better.  I will be be going through such things as how and when you should be using OneDrive vs SharePoint along with common scenarios of when to use each.  By the end I hope to shed some light on things that you can take home with you to help ensure the best Office 365 adoption you can get while utilizing the appropriate solutions. 

As I am writing this the week before Ignite, I am already past 475 registered attendees for this session and can’t wait to see where we go from there. I also can’t wait to get down to Orlando and see some familiar faces and hopefully make some new friends whether at the event or at the always fun after parties.  If you see my walking around or sitting aimlessly by myself come on over and let’s chat!  See everyone soon!