Created
December 22, 2015 19:25
-
-
Save ned1313/7c87d3cbaa0e50022737 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<# | |
.SYNOPSIS | |
This script is intended to apply various policy settings to OneDrive for Business SharePoint sites. | |
.DESCRIPTION | |
The settings and policies include both user configurable and adminstrative options. Different policies can be | |
applied depending on the parameter set invoked. | |
.PARAMETER ApplyPreservationPolicy | |
Optional, switch parameter. When included, all OneDrive for Business sites will be checked to | |
verify that the have the current preservation policy applied. | |
.PARAMETER ApplyVersioning | |
Optional, switch parameter. When included, all OneDrive for Business sites will be checked to | |
verify that the have the current versioning policy applied. | |
.PARAMETER ApplyIRMPolicy | |
Optional, switch parameter. When included, all OneDrive for Business sites will be checked to | |
verify that the have the current IRM policy applied. | |
.INPUTS | |
None | |
.OUTPUTS | |
Log file stored in current script path in logs subfolder | |
.NOTES | |
Version: 1.0 | |
Author: Ned Bellavance | |
Creation Date: 12/7/2015 | |
Purpose/Change: Initial script development | |
- Script requires the presence of the SharePoint Online SDK and SharePoint Online PowerShell module | |
- The passwords for the user accounts should be encrypted using an AES key generated using the following | |
command: | |
$KeyFile = ".\PathtoKey\AES.key" | |
$Key = New-Object Byte[] 32 # You can use 16, 24, or 32 for AES | |
[Security.Cryptography.RNGCryptoServiceProvider]::Create().GetBytes($Key) | |
$Key | out-file $KeyFile | |
- The passwords for these user accounts must be stored in secure files using the command: | |
$PasswordFile = "\\Machine1\SharedPath\Password.txt" | |
$KeyFile = ".\PathtoKey\AES.key" | |
$Key = Get-Content $KeyFile | |
Read-Host -AsSecureString | ConvertFrom-SecureString -key $Key | Out-File $PasswordFile | |
- Before running the script the variables need to be set in the Declarations region | |
.EXAMPLE | |
Apply-OneDriveForBusinessPolicies -ApplyIRMPolicy | |
Runs the script and applies the current IRM Policy specified in the script to all existing OneDrive | |
for Business sites. | |
#> | |
#region---------------------------------------------------------[Initialisations]-------------------------------------------------------- | |
[CmdletBinding()] | |
param( | |
[switch] $ApplyIRMPolicy, | |
[switch] $ApplyVersioning, | |
[switch] $ApplyPreservationPolicy | |
) | |
#endregion---------------------------------------------------------[Initialisations]-------------------------------------------------------- | |
#region----------------------------------------------------------[Declarations]---------------------------------------------------------- | |
#Script Version | |
$sScriptVersion = "1.0" | |
#Log File Info | |
$sLogPath = ".\logs" | |
$sLogName = "Apply-OneDriveForBusinessPolicies_$(Get-Date -f yyyy-MM-dd-hh-mm-ss).log" | |
$sLogFile = Join-Path -Path $sLogPath -ChildPath $sLogName | |
# SPO Admin information | |
$AdminURI = "https://clientname-admin.sharepoint.com" | |
$AdminUserName = "username@clientname.com" | |
$AdminPasswordFile = ".\AdminPwdFile.txt" | |
$keyFile = ".\keyFile.txt" | |
$OneDriveURI = "https://client-my.sharepoint.com" | |
#Preservation Policy information | |
$HoldPolicyName = "Policy Name" | |
#IRM Policy Information | |
$listTitle = "Documents" | |
$PolicyTitle = "Default Policy" | |
$PolicyDescription = "The Default Policy for Client Name" | |
$IrmReject = $false | |
$ProtectionExpirationDate = $null | |
$DisableDocumentBrowserView = $false | |
$AllowPrint = $false | |
$AllowScript = $false | |
$AllowWriteCopy = $false | |
$DocumentAccessExpireDays = 14 | |
$LicenseCacheExpireDays = 14 | |
$GroupName = "" | |
#Versioning Policy Information | |
[int]$MajorVersionLimit = 0 | |
[int]$MajorWithMinorVersionsLimit = 0 | |
[switch]$EnableVersioning = $true | |
[switch]$EnableMinorVersions = $true | |
#endregion----------------------------------------------------------[Declarations]---------------------------------------------------------- | |
#region-----------------------------------------------------------[Functions]------------------------------------------------------------ | |
Function Get-AllOneDriveSite{ | |
[CmdletBinding()] | |
Param( | |
[PSCredential] $AdminCredentials | |
) | |
Add-Content -path $script:sLogFile -value "$(get-date -f s) Starting Get-AllOneDriveSite" -PassThru | ` | |
Write-Output | Write-Verbose | |
$URLs = @() | |
Add-Content -path $script:sLogFile -value "$(get-date -f s) Loading assemblies" -PassThru | ` | |
Write-Output | Write-Verbose | |
#Load Assemblies | |
$loadInfo1 = [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client") | |
$loadInfo2 = [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.Runtime") | |
$loadInfo3 = [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.UserProfiles") | |
Add-Content -path $script:sLogFile -value "$(get-date -f s) Creating SharePoint Credentials" -PassThru | ` | |
Write-Output | Write-Verbose | |
#Create SharePoint credentials | |
$creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($AdminCredentials.UserName, $AdminCredentials.Password) | |
Add-Content -path $script:sLogFile -value "$(get-date -f s) Creating webservice proxy" -PassThru | ` | |
Write-Output | Write-Verbose | |
# Add the path of the User Profile Service to the SPO admin URL, then create a new webservice proxy to access it | |
$proxyaddr = "$script:AdminURI/_vti_bin/UserProfileService.asmx?wsdl" | |
$UserProfileService= New-WebServiceProxy -Uri $proxyaddr -UseDefaultCredential False | |
$UserProfileService.Credentials = $creds | |
Try{ | |
Add-Content -path $script:sLogFile -value "$(get-date -f s) Setting authentication cookie" -PassThru | ` | |
Write-Output | Write-Verbose | |
# Set variables for authentication cookies | |
$strAuthCookie = $creds.GetAuthenticationCookie($AdminURI) | |
$uri = New-Object System.Uri($AdminURI) | |
$container = New-Object System.Net.CookieContainer | |
$container.SetCookies($uri, $strAuthCookie) | |
$UserProfileService.CookieContainer = $container | |
} | |
Catch{ | |
Add-Content -path $script:sLogFile -value "$(get-date -f s) Error encountered when setting authentication cookie. Error is: $_" -PassThru | ` | |
Write-Host -ForegroundColor Red | |
Break | |
} | |
Try{ | |
Add-Content -path $script:sLogFile -value "$(get-date -f s) Retrieving first User Profile" -PassThru | ` | |
Write-Output | Write-Verbose | |
# Sets the first User profile, at index -1 | |
$UserProfileResult = $UserProfileService.GetUserProfileByIndex(-1) | |
} | |
Catch{ | |
Add-Content -path $script:sLogFile -value "$(get-date -f s) Error encountered when getting all User Profiles. Error is: $_" -PassThru | ` | |
Write-Host -ForegroundColor Red | |
return | |
} | |
Try{ | |
$NumProfiles = $UserProfileService.GetUserProfileCount() | |
$i = 1 | |
# As long as the next User profile is NOT the one we started with (at -1)... | |
While ($UserProfileResult.NextValue -ne -1) | |
{ | |
Add-Content -path $script:sLogFile -value "$(get-date -f s) Examining profile $i of $NumProfiles" -PassThru | ` | |
Write-Output | Write-Verbose | |
# Look for the Personal Space object in the User Profile and retrieve it | |
# (PersonalSpace is the name of the path to a user's OneDrive for Business site. Users who have not yet created a | |
# OneDrive for Business site might not have this property set.) | |
$Prop = $UserProfileResult.UserProfile | Where-Object { $_.Name -eq "PersonalSpace" } | |
$Url= $Prop.Values[0].Value | |
# If "PersonalSpace" (which we've copied to $Url) exists, log it to our file... | |
if ($Url) { | |
$URLs += $Url | |
} | |
# And now we check the next profile the same way... | |
$UserProfileResult = $UserProfileService.GetUserProfileByIndex($UserProfileResult.NextValue) | |
$i++ | |
} | |
} | |
Catch{ | |
Add-Content -path $script:sLogFile -value "$(get-date -f s) Error encountered when retrieving Next User Profile. Error is: $_" -PassThru | ` | |
Write-Host -ForegroundColor Red | |
return | |
} | |
return $URLs | |
} | |
function Load-SharePointOnlineClientComponentAssemblies | |
{ | |
[cmdletbinding()] | |
param() | |
process | |
{ | |
# assembly location: C:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI | |
try | |
{ | |
Write-Verbose "Loading Assembly: Microsoft.Office.Client.Policy, Version=16.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" | |
[System.Reflection.Assembly]::Load("Microsoft.Office.Client.Policy, Version=16.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c") | Out-Null | |
Write-Verbose "Loading Assembly: Microsoft.Office.Client.TranslationServices, Version=16.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" | |
[System.Reflection.Assembly]::Load("Microsoft.Office.Client.TranslationServices, Version=16.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c") | Out-Null | |
Write-Verbose "Loading Assembly: Microsoft.SharePoint.Client, Version=16.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" | |
[System.Reflection.Assembly]::Load("Microsoft.SharePoint.Client, Version=16.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c") | Out-Null | |
Write-Verbose "Loading Assembly: Microsoft.SharePoint.Client.DocumentManagement, Version=16.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" | |
[System.Reflection.Assembly]::Load("Microsoft.SharePoint.Client.DocumentManagement, Version=16.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c") | Out-Null | |
Write-Verbose "Loading Assembly: Microsoft.SharePoint.Client.Publishing, Version=16.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" | |
[System.Reflection.Assembly]::Load("Microsoft.SharePoint.Client.Publishing, Version=16.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c") | Out-Null | |
Write-Verbose "Loading Assembly: Microsoft.SharePoint.Client.Runtime, Version=16.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" | |
[System.Reflection.Assembly]::Load("Microsoft.SharePoint.Client.Runtime, Version=16.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c") | Out-Null | |
Write-Verbose "Loading Assembly: Microsoft.SharePoint.Client.Search.Applications, Version=16.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" | |
[System.Reflection.Assembly]::Load("Microsoft.SharePoint.Client.Search.Applications, Version=16.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c") | Out-Null | |
Write-Verbose "Loading Assembly: Microsoft.SharePoint.Client.Search, Version=16.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" | |
[System.Reflection.Assembly]::Load("Microsoft.SharePoint.Client.Search, Version=16.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c") | Out-Null | |
Write-Verbose "Loading Assembly: Microsoft.SharePoint.Client.Taxonomy, Version=16.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" | |
[System.Reflection.Assembly]::Load("Microsoft.SharePoint.Client.Taxonomy, Version=16.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c") | Out-Null | |
Write-Verbose "Loading Assembly: Microsoft.SharePoint.Client.UserProfiles, Version=16.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" | |
[System.Reflection.Assembly]::Load("Microsoft.SharePoint.Client.UserProfiles, Version=16.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c") | Out-Null | |
return $true | |
} | |
catch | |
{ | |
if($_.Exception.Message -match "Could not load file or assembly") | |
{ | |
throw "Unable to load the SharePoint Server 2013 Client Components.`nDownload Location: http://www.microsoft.com/en-us/download/details.aspx?id=42038" | |
} | |
else | |
{ | |
throw "Unknown Error: $_" | |
} | |
return $false | |
} | |
} | |
} | |
function Load-SharePointOnlineModule | |
{ | |
[cmdletbinding()] | |
param() | |
process | |
{ | |
do | |
{ | |
# Installation location: C:\Program Files\SharePoint Online Management Shell\Microsoft.Online.SharePoint.PowerShell | |
$spoModule = Get-Module -Name Microsoft.Online.SharePoint.PowerShell -ErrorAction SilentlyContinue | |
if(-not $spoModule) | |
{ | |
try | |
{ | |
Import-Module Microsoft.Online.SharePoint.PowerShell -DisableNameChecking | |
return $true | |
} | |
catch | |
{ | |
if($_.Exception.Message -match "Could not load file or assembly") | |
{ | |
throw "Unable to load the SharePoint Online Management Shell.`nDownload Location: http://www.microsoft.com/en-us/download/details.aspx?id=35588" | |
} | |
else | |
{ | |
throw "Unknown Error:$_" | |
} | |
return $false | |
} | |
} | |
else | |
{ | |
return $true | |
} | |
} | |
while(-not $spoModule) | |
} | |
} | |
function Set-Versioning | |
{ | |
[cmdletbinding()] | |
param( | |
[parameter(Mandatory=$true)][Microsoft.SharePoint.Client.ClientContext] $context, | |
[parameter(Mandatory=$true)][Microsoft.SharePoint.Client.List]$List, | |
[parameter(Mandatory=$false)][int]$MajorVersionLimit = 0, | |
[parameter(Mandatory=$false)][int]$MajorWithMinorVersionsLimit = 0, | |
[parameter(Mandatory=$false)][switch]$EnableVersioning, | |
[parameter(Mandatory=$false)][switch]$EnableMinorVersions | |
) | |
process | |
{ | |
Add-Content -path $script:sLogFile -value "$(get-date -f s) Applying Versioning Configuration on '$($List.Title)'" -PassThru | ` | |
Write-Output | Write-Verbose | |
$list.EnableVersioning = $EnableVersioning.IsPresent | |
Add-Content -path $script:sLogFile -value "$(get-date -f s) EnableVersioning set to $($list.EnableVersioning)" -PassThru | ` | |
Write-Output | Write-Verbose | |
$list.EnableMinorVersions = $EnableMinorVersions.IsPresent | |
Add-Content -path $script:sLogFile -value "$(get-date -f s) EnableMinorVersions set to $($list.EnableMinorVersions)" -PassThru | ` | |
Write-Output | Write-Verbose | |
$list.MajorVersionLimit = $MajorVersionLimit | |
Add-Content -path $script:sLogFile -value "$(get-date -f s) MajorVersionLimit set to $($list.MajorVersionLimit)" -PassThru | ` | |
Write-Output | Write-Verbose | |
$list.MajorWithMinorVersionsLimit = $MajorWithMinorVersionsLimit | |
Add-Content -path $script:sLogFile -value "$(get-date -f s) MajorWithMinorVersionsLimit set to $($list.MajorWithMinorVersionsLimit)" -PassThru | ` | |
Write-Output | Write-Verbose | |
Add-Content -path $script:sLogFile -value "$(get-date -f s) Committing Versioning configuration settings on '$($list.Title)'" -PassThru | ` | |
Write-Output | Write-Verbose | |
$list.Update() | |
$context.Load($list) | |
$context.ExecuteQuery() | |
} | |
} | |
function Set-IrmConfiguration | |
{ | |
[cmdletbinding()] | |
param( | |
[parameter(Mandatory=$true)][Microsoft.SharePoint.Client.ClientContext] $context, | |
[parameter(Mandatory=$true)][Microsoft.SharePoint.Client.List]$List, | |
[parameter(Mandatory=$true)][string]$PolicyTitle, | |
[parameter(Mandatory=$true)][string]$PolicyDescription, | |
[parameter(Mandatory=$false)][switch]$IrmReject, | |
[parameter(Mandatory=$false)][string]$ProtectionExpirationDate, | |
[parameter(Mandatory=$false)][switch]$DisableDocumentBrowserView, | |
[parameter(Mandatory=$false)][switch]$AllowPrint, | |
[parameter(Mandatory=$false)][switch]$AllowScript, | |
[parameter(Mandatory=$false)][switch]$AllowWriteCopy, | |
[parameter(Mandatory=$false)][int]$DocumentAccessExpireDays, | |
[parameter(Mandatory=$false)][int]$LicenseCacheExpireDays, | |
[parameter(Mandatory=$false)][string]$GroupName | |
) | |
process | |
{ | |
Add-Content -path $script:sLogFile -value "$(get-date -f s) Applying IRM Configuration on '$($List.Title)'" -PassThru | ` | |
Write-Output | Write-Verbose | |
# reset the value to the default settings | |
Add-Content -path $script:sLogFile -value "$(get-date -f s) Reset the value to the default settings" -PassThru | ` | |
Write-Output | Write-Verbose | |
$list.InformationRightsManagementSettings.Reset() | |
$list.IrmEnabled = $true | |
# IRM Policy title and description | |
Add-Content -path $script:sLogFile -value "$(get-date -f s) IRM Policy title and description" -PassThru | ` | |
Write-Output | Write-Verbose | |
$list.InformationRightsManagementSettings.PolicyTitle = $PolicyTitle | |
$list.InformationRightsManagementSettings.PolicyDescription = $PolicyDescription | |
# Set additional IRM library settings | |
Add-Content -path $script:sLogFile -value "$(get-date -f s) Set additional IRM library settings" -PassThru | ` | |
Write-Output | Write-Verbose | |
# Do not allow users to upload documents that do not support IRM | |
Add-Content -path $script:sLogFile -value "$(get-date -f s) IRMReject set" -PassThru | ` | |
Write-Output | Write-Verbose | |
$list.IrmReject = $IrmReject.IsPresent | |
$parsedDate = Get-Date | |
if([DateTime]::TryParse($ProtectionExpirationDate, [ref]$parsedDate)) | |
{ | |
# Stop restricting access to the library at <date> | |
Add-Content -path $script:sLogFile -value "$(get-date -f s) IRM Expire and Date set" -PassThru | ` | |
Write-Output | Write-Verbose | |
$list.IrmExpire = $true | |
$list.InformationRightsManagementSettings.DocumentLibraryProtectionExpireDate = $ProtectionExpirationDate | |
} | |
# Prevent opening documents in the browser for this Document Library | |
Add-Content -path $script:sLogFile -value "$(get-date -f s) Disable Document Browser" -PassThru | ` | |
Write-Output | Write-Verbose | |
$list.InformationRightsManagementSettings.DisableDocumentBrowserView = $DisableDocumentBrowserView.IsPresent | |
# Configure document access rights | |
Add-Content -path $script:sLogFile -value "$(get-date -f s) Configure document access rights" -PassThru | ` | |
Write-Output | Write-Verbose | |
# Allow viewers to print | |
$list.InformationRightsManagementSettings.AllowPrint = $AllowPrint.IsPresent | |
# Allow viewers to run script and screen reader to function on downloaded documents | |
$list.InformationRightsManagementSettings.AllowScript = $AllowScript.IsPresent | |
# Allow viewers to write on a copy of the downloaded document | |
$list.InformationRightsManagementSettings.AllowWriteCopy = $AllowWriteCopy.IsPresent | |
if($DocumentAccessExpireDays) | |
{ | |
# After download, document access rights will expire after these number of days (1-365) | |
Add-Content -path $script:sLogFile -value "$(get-date -f s) Configure DocumentAccessExpireDays" -PassThru | ` | |
Write-Output | Write-Verbose | |
$list.InformationRightsManagementSettings.EnableDocumentAccessExpire = $true | |
$list.InformationRightsManagementSettings.DocumentAccessExpireDays = $DocumentAccessExpireDays | |
} | |
# Set group protection and credentials interval | |
if($LicenseCacheExpireDays) | |
{ | |
# Users must verify their credentials using this interval (days) | |
Add-Content -path $script:sLogFile -value "$(get-date -f s) Configure LicenseCacheExpireDays" -PassThru | ` | |
Write-Output | Write-Verbose | |
$list.InformationRightsManagementSettings.EnableLicenseCacheExpire = $true | |
$list.InformationRightsManagementSettings.LicenseCacheExpireDays = $LicenseCacheExpireDays | |
} | |
if($GroupName) | |
{ | |
# Allow group protection. Default group: | |
Add-Content -path $script:sLogFile -value "$(get-date -f s) Configure EnableGroupProtection" -PassThru | ` | |
Write-Output | Write-Verbose | |
$list.InformationRightsManagementSettings.EnableGroupProtection = $true | |
$list.InformationRightsManagementSettings.GroupName = $GroupName | |
} | |
Add-Content -path $script:sLogFile -value "$(get-date -f s) Committing IRM configuration settings on '$($list.Title)'" -PassThru | ` | |
Write-Output | Write-Verbose | |
$list.InformationRightsManagementSettings.Update() | |
Write-Verbose "Update List" | |
$list.Update() | |
Write-Verbose "Load List" | |
$context.Load($list) | |
Write-Verbose "Execute Query" | |
$context.ExecuteQuery() | |
} | |
} | |
function Test-Versioning | |
{ | |
[cmdletbinding()] | |
param( | |
[parameter(Mandatory=$true)][Microsoft.SharePoint.Client.ClientContext] $context, | |
[parameter(Mandatory=$true)][Microsoft.SharePoint.Client.List]$List, | |
[parameter(Mandatory=$false)][int]$MajorVersionLimit, | |
[parameter(Mandatory=$false)][int]$MajorWithMinorVersionsLimit, | |
[parameter(Mandatory=$false)][switch]$EnableVersioning, | |
[parameter(Mandatory=$false)][switch]$EnableMinorVersions | |
) | |
process | |
{ | |
Add-Content -path $script:sLogFile -value "$(get-date -f s) Testing Versioning Configuration on '$($List.Title)'" -PassThru | ` | |
Write-Output | Write-Verbose | |
$match = $true | |
if($list.EnableVersioning -ne $EnableVersioning.IsPresent){Write-Verbose "EnableVersioning does not match";$match = $false} | |
elseif($list.EnableMinorVersions -ne $EnableMinorVersions.IsPresent){Write-Verbose "EnableMinorVersions does not match";$match = $false} | |
elseif($list.MajorVersionLimit -ne $MajorVersionLimit){Write-Verbose "MajorVersionLimit does not match";$match = $false} | |
elseif($list.MajorWithMinorVersionsLimit -ne $MajorWithMinorVersionsLimit){Write-Verbose "MajorWithMinorVersionsLimit does not match";$match = $false} | |
return $match | |
} | |
} | |
function Test-IrmConfiguration | |
{ | |
[cmdletbinding()] | |
param( | |
[parameter(Mandatory=$true)][Microsoft.SharePoint.Client.ClientContext] $context, | |
[parameter(Mandatory=$true)][Microsoft.SharePoint.Client.List]$List, | |
[parameter(Mandatory=$true)][string]$PolicyTitle, | |
[parameter(Mandatory=$true)][string]$PolicyDescription, | |
[parameter(Mandatory=$false)][switch]$IrmReject, | |
[parameter(Mandatory=$false)][string]$ProtectionExpirationDate, | |
[parameter(Mandatory=$false)][switch]$DisableDocumentBrowserView, | |
[parameter(Mandatory=$false)][switch]$AllowPrint, | |
[parameter(Mandatory=$false)][switch]$AllowScript, | |
[parameter(Mandatory=$false)][switch]$AllowWriteCopy, | |
[parameter(Mandatory=$false)][int]$DocumentAccessExpireDays, | |
[parameter(Mandatory=$false)][int]$LicenseCacheExpireDays, | |
[parameter(Mandatory=$false)][string]$GroupName | |
) | |
process | |
{ | |
Add-Content -path $script:sLogFile -value "$(get-date -f s) Testing IRM Configuration on '$($List.Title)'" -PassThru | ` | |
Write-Output | Write-Verbose | |
$context.Load($list.InformationRightsManagementSettings) | |
$context.ExecuteQuery() | |
$match = $true | |
if(-not $list.IrmEnabled){Write-Verbose "IRM not enabled";$match = $false} | |
elseif($list.InformationRightsManagementSettings.PolicyTitle -ne $PolicyTitle -or $list.InformationRightsManagementSettings.PolicyDescription -ne $PolicyDescription){Write-Verbose "PolicyTitle or PolicyDescription does not match" ; $match = $false} | |
elseif($list.IrmReject -ne $IrmReject.IsPresent){Write-Verbose "IrmReject does not match";$match = $false} | |
elseif($IrmReject.IsPresent -and $list.InformationRightsManagementSettings.DocumentLibraryProtectionExpireDate -ne $ProtectionExpirationDate){Write-Verbose "ProtectionExpirationDate does not match";$match = $false} | |
elseif($list.InformationRightsManagementSettings.DisableDocumentBrowserView -ne $DisableDocumentBrowserView.IsPresent){Write-Verbose "DisableDocumentBrowserView does not match";$match = $false} | |
elseif($list.InformationRightsManagementSettings.AllowPrint -ne $AllowPrint.IsPresent){Write-Verbose "AllowPrint does not match";$match = $false} | |
elseif($list.InformationRightsManagementSettings.AllowScript -ne $AllowScript.IsPresent){Write-Verbose "AllowScript does not match";$match = $false} | |
elseif($list.InformationRightsManagementSettings.AllowWriteCopy -ne $AllowWriteCopy.IsPresent){Write-Verbose "AllowWriteCopy does not match";$match = $false} | |
elseif($list.InformationRightsManagementSettings.DocumentAccessExpireDays -ne $DocumentAccessExpireDays){Write-Verbose "DocumentAccessExpireDays does not match";$match = $false} | |
elseif($list.InformationRightsManagementSettings.LicenseCacheExpireDays -ne $LicenseCacheExpireDays){Write-Verbose "LicenseCacheExpireDays does not match";$match = $false} | |
elseif($list.InformationRightsManagementSettings.GroupName -ne $GroupName){Write-Verbose "GroupName does not match";$match = $false} | |
return $match | |
} | |
} | |
Function ApplyVersioningAndIRM{ | |
[CmdletBinding()] | |
param( | |
[PSCredential] $AdminCredential, | |
[string[]] $webUrls, | |
[switch] $Versioning, | |
[switch] $IRM | |
) | |
Add-Content -path $script:sLogFile -value "$(get-date -f s) Connecting to SharePoint Online" -PassThru | ` | |
Write-Output | Write-Verbose | |
# connect to Office365 first, required for SharePoint Online cmdlets to run | |
Connect-SPOService -Url $script:AdminURI -Credential $AdminCredential | |
Add-Content -path $script:sLogFile -value "$(get-date -f s) Begining loop of URLs" -PassThru | ` | |
Write-Output | Write-Verbose | |
# enumerate each of the specified site URLs | |
foreach($webUrl in $webUrls) | |
{ | |
$grantedSiteCollectionAdmin = $false | |
try | |
{ | |
Add-Content -path $script:sLogFile -value "$(get-date -f s) Establishing client context for $webUrl" -PassThru | ` | |
Write-Output | Write-Verbose | |
# establish the client context and set the credentials to connect to the site | |
$clientContext = New-Object Microsoft.SharePoint.Client.ClientContext($webUrl) | |
$clientContext.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($AdminCredential.UserName, $AdminCredential.Password) | |
# initialize the site and web context | |
$clientContext.Load($clientContext.Site) | |
$clientContext.Load($clientContext.Web) | |
$clientContext.ExecuteQuery() | |
# load and ensure the tenant admin user account if present on the target SharePoint site | |
$tenantAdminUser = $clientContext.Web.EnsureUser($AdminCredential.UserName) | |
$clientContext.Load($tenantAdminUser) | |
$clientContext.ExecuteQuery() | |
# check if the tenant admin is a site admin | |
if( -not $tenantAdminUser.IsSiteAdmin ) | |
{ | |
Add-Content -path $script:sLogFile -value "$(get-date -f s) Temporarily granting site permission to admin account" -PassThru | ` | |
Write-Output | Write-Verbose | |
try | |
{ | |
# grant the tenant admin temporary admin rights to the site collection | |
Set-SPOUser -Site $clientContext.Site.Url -LoginName $AdminCredential.UserName -IsSiteCollectionAdmin $true | Out-Null | |
$grantedSiteCollectionAdmin = $true | |
} | |
catch | |
{ | |
Write-Error $_.Exception | |
return | |
} | |
} | |
try | |
{ | |
# load the list orlibrary using CSOM | |
$list = $null | |
$list = $clientContext.Web.Lists.GetByTitle($listTitle) | |
$clientContext.Load($list) | |
$clientContext.ExecuteQuery() | |
if($IRM){ | |
#if(!$script:ProtectionExpirationDate){Remove-Variable $script:ProtectionExpirationDate} | |
Write-Verbose "Execute IRM on $webUrl" | |
if(Test-IrmConfiguration -context $clientContext -List $list -PolicyTitle $PolicyTitle -PolicyDescription $PolicyDescription -IrmReject:$IrmReject ` | |
-ProtectionExpirationDate $ProtectionExpirationDate -DisableDocumentBrowserView:$DisableDocumentBrowserView -AllowPrint:$AllowPrint -AllowScript:$AllowScript ` | |
-AllowWriteCopy:$AllowWriteCopy -DocumentAccessExpireDays $DocumentAccessExpireDays -LicenseCacheExpireDays $LicenseCacheExpireDays -GroupName $GroupName){ | |
Add-Content -path $script:sLogFile -value "$(get-date -f s) IRM settings match for $webUrl" -PassThru | ` | |
Write-Output | Write-Verbose | |
} | |
else{ | |
#apply the IRM configuration detailed in the Declarations region | |
Set-IrmConfiguration -context $clientContext -List $list -PolicyTitle $script:PolicyTitle -PolicyDescription $script:PolicyDescription -IrmReject:$script:IrmReject ` | |
-ProtectionExpirationDate $script:ProtectionExpirationDate -DisableDocumentBrowserView:$scriptDisableDocumentBrowserView -AllowPrint:$script:AllowPrint ` | |
-AllowScript:$script:AllowScript -AllowWriteCopy:$script:AllowWriteCopy -GroupName $script:GroupName -DocumentAccessExpireDays $script:DocumentAccessExpireDays ` | |
-LicenseCacheExpireDays $script:LicenseCacheExpireDays | |
} | |
} | |
if($Versioning){ | |
Write-Verbose "Execute Versioning on $webUrl" | |
if(Test-Versioning -context $clientContext -List $list -MajorVersionLimit $MajorVersionLimit -MajorWithMinorVersionsLimit $MajorWithMinorVersionsLimit ` | |
-EnableVersioning:$EnableVersioning -EnableMinorVersions:$EnableMinorVersions){ | |
Add-Content -path $script:sLogFile -value "$(get-date -f s) Versioning settings match for $webUrl" -PassThru | ` | |
Write-Output | Write-Verbose | |
} | |
else{ | |
Set-Versioning -context $clientContext -List $list -MajorVersionLimit $script:MajorVersionLimit -MajorWithMinorVersionsLimit $script:MajorWithMinorVersionsLimit ` | |
-EnableVersioning:$script:EnableVersioning -EnableMinorVersions:$script:EnableMinorVersion | |
} | |
} | |
} | |
catch | |
{ | |
throw "Error setting IRM or versioning configuration on site: $webUrl.`nError Details: $_" | |
} | |
} | |
finally | |
{ | |
if($grantedSiteCollectionAdmin) | |
{ | |
Add-Content -path $script:sLogFile -value "$(get-date -f s) Removing temporary admin rights from $webUrl" -PassThru | ` | |
Write-Output | Write-Verbose | |
# remove the temporary admin rights to the site collection | |
Set-SPOUser -Site $clientContext.Site.Url -LoginName $AdminCredential.UserName -IsSiteCollectionAdmin $false | Out-Null | |
} | |
} | |
} | |
Disconnect-SPOService -ErrorAction SilentlyContinue | |
} | |
Function SetPreservationPolicy{ | |
[CmdletBinding()] | |
param( | |
[PSCredential] $AdminCred, | |
[string[]] $URLs, | |
[string] $HoldPolicyName, | |
[switch] $WhatIf | |
) | |
Add-Content -path $script:sLogFile -value "$(get-date -f s) Connecting to Compliance Center" -PassThru | ` | |
Write-Output | Write-Verbose | |
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.compliance.protection.outlook.com/powershell-liveid/ -Credential $AdminCred -Authentication Basic -AllowRedirection | |
Import-PSSession $Session | |
Add-Content -path $script:sLogFile -value "$(get-date -f s) Retrieving current preservation policy and applied URLs" -PassThru | ` | |
Write-Output | Write-Verbose | |
$policy = Get-HoldCompliancePolicy $HoldPolicyName | |
$CurrentURLs = @() | |
foreach($entry in $policy.SharePointLocation){$CurrentURLs += "$($entry.Name)/"} | |
foreach($URL in $URLs){ | |
if($CurrentURLs -notcontains $URL){ | |
Add-Content -path $script:sLogFile -value "$(get-date -f s) Applying policy $HoldPolicyName to $URL" -PassThru | ` | |
Write-Output | Write-Verbose | |
Set-HoldCompliancePolicy $HoldPolicyName -AddSharePointLocation $URL -WhatIf:$WhatIf | |
} | |
else{ | |
Add-Content -path $script:sLogFile -value "$(get-date -f s) Policy already exists for $URL" -PassThru | ` | |
Write-Output | Write-Verbose | |
} | |
} | |
Remove-PSSession | |
} | |
#endregion-----------------------------------------------------------[Functions]------------------------------------------------------------ | |
#region-----------------------------------------------------------[Execution]------------------------------------------------------------ | |
if(-not(Test-Path $sLogPath)){ | |
New-Item -Path $sLogPath -ItemType Directory | |
} | |
Add-Content -path $script:sLogFile -value "$(get-date -f s) Log started" -PassThru | ` | |
Write-Output | Write-Verbose | |
#Create Admin credential | |
$Key = Get-Content $keyFile | |
$AdminCredential = New-Object -Typename System.Management.Automation.PSCredential -Argumentlist $AdminUserName, (Get-Content $AdminPasswordFile | ConvertTo-SecureString -Key $Key) | |
#Check that options were passed | |
if(-not $ApplyIRMPolicy -and -not $ApplyVersioning -and -not $ApplyPreservationPolicy){ | |
Add-Content -path $script:sLogFile -value "$(get-date -f s) No option selected, script will exit without making changes" -PassThru | ` | |
Write-Output | Write-Verbose | |
exit | |
} | |
$stubs = $null | |
#Load Module and Assemblies | |
try{ | |
Load-SharePointOnlineModule | |
Load-SharePointOnlineClientComponentAssemblies | |
} | |
catch{ | |
Add-Content -path $script:sLogFile -value "$(get-date -f s) Error loading module and assemblies. Script will exit. Error is: $_" -PassThru | ` | |
Write-Host -ForegroundColor Red | |
exit | |
} | |
try{ | |
$stubs = Get-AllOneDriveSite -AdminCredentials $AdminCredential | |
} | |
catch{ | |
Add-Content -path $script:sLogFile -value "$(get-date -f s) Error running Get-AllOneDriveSite. Script will exit. Error is: $_" -PassThru | ` | |
Write-Host -ForegroundColor Red | |
exit | |
} | |
$URLs = @() | |
foreach($stub in $stubs){ | |
$URLs += $OneDriveURI + $stub | |
} | |
if(($ApplyIRMPolicy -or $ApplyVersioning) -and $stubs){ | |
try{ | |
ApplyVersioningAndIRM -AdminCredential $AdminCredential -webUrls $URLs -Versioning:$script:ApplyVersioning -IRM:$script:ApplyIRMPolicy | |
} | |
catch{ | |
Add-Content -path $script:sLogFile -value "$(get-date -f s) Errors encountered running ApplyVersioningAndIRM. Error is: $_" -PassThru | ` | |
Write-Host -ForegroundColor Red | |
} | |
} | |
#Check for Preservation Policy Pararmeter | |
if($ApplyPreservationPolicy -and $stubs){ | |
try{ | |
SetPreservationPolicy -AdminCred $AdminCredential -URLs $URLs -HoldPolicyName $HoldPolicyName | |
} | |
catch{ | |
Add-Content -path $script:sLogFile -value "$(get-date -f s) Errors encountered running SetPreservationPolicy. Error is: $_" -PassThru | ` | |
Write-Host -ForegroundColor Red | |
} | |
} | |
#Script Execution goes here | |
Add-Content -path $script:sLogFile -value "$(get-date -f s) Log complete" -PassThru | ` | |
Write-Output | Write-Verbose | |
#endregion-----------------------------------------------------------[Execution]------------------------------------------------------------ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment