Instantly share code, notes, and snippets.

Embed
What would you like to do?
PowerShell script which processes an Azure AD B2B invitation CSV file (augmented with an `SPGroups` fields) and grants access permissions to SharePoint Online accordingly.
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True)]
[string]$CSVFilename,
[Parameter(Mandatory=$True)]
[string]$SiteUrl,
[Parameter()]
$Credentials
)
function AddB2BUsersToSite() {
# Check that the CSV file exists
if (-not (Test-Path $CSVFilename)) {
Write-Error "Could not find CSV-file. Please check the path and try again."
return
}
# Prompt for credentials (if not passed in as parameter)
if (-not $Credentials) {
Write-Verbose "Credentials not supplied, prompting for them."
$Credentials = Get-Credential -Message "Login to $siteUrl"
}
# Connect to SPOnline
try {
Write-Debug "Connecting to SharePoint"
Connect-SPOnline -Url $SiteUrl -Credentials $Credentials
$web = Get-SPOWeb
} catch {
Write-Error "Could not connect to $siteUrl. Please check the provided url and credentials and try again."
return
}
# Open the CSV-file
Write-Debug "Opening CSV file"
$csv = Import-Csv -Delimiter "," $CSVFilename
# Loop through all users
$csv | ForEach-Object {
$row = $_
$loginName = $row.Email
$spgroups = $row.SPGroups
# Add the user to the hidden user information list
# This will also make the user appear in the PeoplePicker dialog
Write-Output "Adding $loginName to site"
Write-Debug "Ensuring that user is present"
$user = $web.EnsureUser($loginName)
$web.Context.ExecuteQuery()
# Add the user to the specified groups
Write-Verbose "Adding user to groups"
if ($spgroups) {
$spgroups -split '\+' | ForEach-Object {
$groupName = $_.Trim()
Write-Verbose "- Adding user to group: $groupName"
Add-SPOUserToGroup -identity $groupName -LoginName $loginName
}
}
}
}
# Main
try {
AddB2BUsersToSite
} finally {
try {Disconnect-SPOnline -ErrorAction SilentlyContinue } catch {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment