Accéder au contenu principal

SharePoint Online: Script PowerShell pour désactiver l’Option IRM des sites SPO non autorisés

 Office 365 possède l’option de gestion des droits de contenu basé sur les modules IRM. Cette option est soumise à license très élevée alors que son activation est globale.

Le fait est que lors de l’activation du module sur le tenant Office 365, n’importe quel content manager de site peut activer cette option dans sa propre liste. Une fois cette activation effectuée dans une liste de ce site, tous les utilisateurs y accédant devront avoir une licence E3.

Ainsi pour limiter ce gap de licence, le script suivant en préparant d’abord le fichier CSV d’exclusion:

SiteCollectionURL;

https://mytenant.sharepoint.com/sites/mysitecollwithIRMaccepted;

Le script PowerShell va obtenir tous les sites du tenant avec les commandes suivantes:

$sitesInfo1 = Get-SPOSite -Template "STS#0" -IncludePersonalSite:$false -Limit ALL | Sort-Object -Property url | Select *

$sitesInfo2 = Get-SPOSite -Template "GROUP#0" -IncludePersonalSite:$false -Limit ALL | Sort-Object -Property url | Select *

$sitesInfo = $sitesInfo2 + $sitesInfo1 | Sort url

Basé sur cette liste de collections, le script va alors bouclé dans toutes les listes de tous les sous-sites pour vérifier le status de l’option IRM:

  • S’il est désactivé: le script passe à la liste suivante et log le statut
  • S’il est activé: le script désactive l’option et enregistre le changement dans le log

Une fois terminé, le script va alors envoyé le log zippé par email avec un résumé des désactivations effectuées dans le body du mail.

Le script complet est le siuvant:

[string]$GLOBAL:Logtofile = ""
[string]$GLOBAL:LogtoEmail = ""

[string]$username = "Adminaccount@tenant.onmicrosoft.com"
[string]$PwdTXTPath = "C:\SECUREDPWD\ExportedPWD-$($username).txt"

[string]$CSVExclusionFilePath = "C:\IRMCHECK\SiteCollectionsWithAuthorizedIRM.csv"

[string]$EmailAddressFrom = "supportteam@Yourdomain.com"
[string]$EmailAddressToSend = "supportteam@Yourdomain.com"
[string]$EmailSubject = "SHAREPOINT ONLINE IRM CHECK - "+ $(Get-Date).ToString("yyyy-MM-dd-hh:mm")
[string]$EmailSMTPServer = "smtp.Yourdomain.net"
[string]$EmailSMTPPort = "25"
$EmailencodingMail = [System.Text.Encoding]::UTF8

[string]$AllSiteWithListenableIRMLog = "AllSiteWithListenableIRM.log"
[string]$FolderDestinationLogFile = "D:\IRMCHECK\LOGS\"
[string]$DestinationLogFilePath = ""
[string]$ZippedLogFilePath = ""
[string]$MyRootFolderListURL = ""
$OFS = "`r`n"

[System.Diagnostics.Stopwatch] $sw;
$sw = New-Object System.Diagnostics.StopWatch
$sw.Start()

function Load-DLLandAssemblies
{
     [string]$defaultDLLPath = ""
    # Load assemblies to PowerShell session
    $defaultDLLPath = "C:\Program Files\SharePoint Online Management Shell\Microsoft.Online.SharePoint.PowerShell\Microsoft.SharePoint.Client.dll"
    [System.Reflection.Assembly]::LoadFile($defaultDLLPath)

    $defaultDLLPath = "C:\Program Files\SharePoint Online Management Shell\Microsoft.Online.SharePoint.PowerShell\Microsoft.SharePoint.Client.Runtime.dll"
    [System.Reflection.Assembly]::LoadFile($defaultDLLPath)

    $defaultDLLPath = "C:\Program Files\SharePoint Online Management Shell\Microsoft.Online.SharePoint.PowerShell\Microsoft.Online.SharePoint.Client.Tenant.dll"
    [System.Reflection.Assembly]::LoadFile($defaultDLLPath)
}

function Get-SPOWebs(){
param(
   $Url = $(throw "Please provide a Site Collection Url"),
   $Credential = $(throw "Please provide a Credentials")
)

  $context = New-Object Microsoft.SharePoint.Client.ClientContext($Url) 
  $context.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Credential.UserName,$Credential.Password)
  $context.RequestTimeout = 1000000 # milliseconds
  $web = $context.Web
  $context.Load($web)
  $context.Load($web.Webs)
  $context.ExecuteQuery()
  foreach($web in $web.Webs)
  {
       Get-SPOWebs -Url $web.Url -Credential $Credential
       $web
  }
}

function Check-All-SPOWebLists(){
param(
   $Url = $(throw "Please provide a Site Collection Url"),
   $Credential = $(throw "Please provide a Credentials")
)
    $GLOBAL:Logtofile += " ------------------------------------------------------------------------------------ " + $OFS
    $GLOBAL:Logtofile += " Checks into the Subsite: "+ $Url + $OFS
   
    $context = New-Object Microsoft.SharePoint.Client.ClientContext($Url)
    $context.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Credential.UserName,$Credential.Password)
    $context.RequestTimeout = 1000000 # milliseconds
    $web = $context.Web
    $Mylists = $web.Lists;
    $Context.Load($Mylists)
    $Context.ExecuteQuery();
    Write-host "     -------------------- CHECK IN LISTS -------------------- "
    foreach($myList in $MyLists)
     {
        Write-host "           ==== List Name:", $mylist.Title  -ForegroundColor Magenta
        if($mylist.IrmEnabled)
         {
            Write-host "                IRM Status (IrmEnabled):", $mylist.IrmEnabled -ForegroundColor Red
            Write-host "                >>> NEED TO CONTROL OR DISABLE THE SETTING" -ForegroundColor Red
           
            # GET the Owner if possible ??
           
            #Force the IRM Disable at the list level
            $mylist.IrmEnabled = $false
             $mylist.Update()
            $Context.ExecuteQuery()
                 
            #Logging the change
            $GLOBAL:Logtofile += " IRM ACTIVE from the list: "+ $mylist.Title +" - in SPWeb: "+ $Url + $OFS
            $GLOBAL:LogtoEmail += " IRM ACTIVE from the list: "+ $mylist.Title +" - in SPWeb: "+ $Url + $OFS
        }
        else
        {
            Write-host "                IRM Status (IrmEnabled):", $mylist.IrmEnabled -ForegroundColor Green
            $GLOBAL:Logtofile += "   IRM Not active from the list: "+ $mylist.Title +" - in SPWeb: "+ $Url + $OFS
        }
    }
    $GLOBAL:Logtofile += " ------------------------------------------------------------------------------------ " + $OFS

}

cls
Write-Host " ---------------------------------------------- "
Load-DLLandAssemblies
Write-Host " ---------------------------------------------- "

$secureStringPwd = ConvertTo-SecureString -string (Get-Content $PwdTXTPath)
$adminCreds = New-Object System.Management.Automation.PSCredential $username, $secureStringPwd

Connect-SPOService -Url https://tenant-admin.sharepoint.com -credential $adminCreds -ErrorAction SilentlyContinue -ErrorVariable Err

Write-host " -------------------------------------------------------------------------------------------- " -ForegroundColor green
$SiteToExcludeList = Import-Csv -encoding UTF8 $CSVExclusionFilePath -delimiter ";"
#$SiteToExcludeList | Format-Table
Write-host "   >>> CSV File content loaded:", $CSVExclusionFilePath, "- Total Lines:", $SiteToExcludeList.count -ForegroundColor Yellow
Write-host " -------------------------------------------------------------------------------------------- " -ForegroundColor green

$TempPathFilename = $(Get-Date).ToString("yyyyMMdd-hhmmss-fff")+"_"+ $AllSiteWithListenableIRMLog
$DestinationLogFilePath = Join-Path -Path $FolderDestinationLogFile -ChildPath $TempPathFilename
if (Test-Path $DestinationLogFilePath)
{
    Remove-Item $DestinationLogFilePath -Force
}

#Retrieve all site collection infos (GroupSite and Classic TeamSite)
$sitesInfo1 = Get-SPOSite -Template "STS#0" -IncludePersonalSite:$false  -Limit ALL | Sort-Object -Property url | Select *
$sitesInfo2 = Get-SPOSite -Template "GROUP#0" -IncludePersonalSite:$false  -Limit ALL | Sort-Object -Property url | Select *

$sitesInfo = $sitesInfo2 + $sitesInfo1  | Sort url
#$sitesInfo = $sitesInfo1  | Sort url | Select-Object -First 2 #TO CHECK ONLY THE FIRST 2 CLASSIC TEAMSITE COLLECTION

Write-Host "--------------------------------------------------------------------------------------------"
Write-Host " =>>>>>>>  Site collections number to check:", $sitesInfo.count -ForegroundColor Magenta
Write-Host "--------------------------------------------------------------------------------------------"

foreach($SiteToExclude in $SiteToExcludeList)
{
    $sitesInfo = $sitesInfo | where {$_.url -ne $SiteToExclude.SiteCollectionURL} #remove all the excluded items from the site list
}

Write-Host "--------------------------------------------------------------------------------------------"
Write-Host " =>>>>>>>  Site collections number to check:", $sitesInfo.count -ForegroundColor Magenta
Write-Host "--------------------------------------------------------------------------------------------"

$GLOBAL:Logtofile += "--------------------------------------------------------------------------------------------" + $OFS
$GLOBAL:Logtofile +=  " =>>>>>>>  Site collections number to check: "+ $($sitesInfo.count) + $OFS
$GLOBAL:Logtofile +=  "--------------------------------------------------------------------------------------------" + $OFS

#Retrieve and print all sites
foreach ($site in $sitesInfo)
{
    #$SiteToExcludeList |Where-Object {$_.SiteCollectionURL -match $site.Url}

    Write-Host "==================================================================================================="
    Write-Host " => SPO Site collection:", $site.Url, "- Title:", $site.Title -ForegroundColor green
    Write-Host "   => External Sharing:", $site.SharingCapability, "- Site Template Used:", $site.Template
    Write-Host "--------------------------------------------------------------------------------------------"

    $GLOBAL:Logtofile += "===================================================================================================" + $OFS
    $GLOBAL:Logtofile += " => SPO Site collection: "+ $($site.Url) +" - Title: "+ $($site.Title) + $OFS
    $GLOBAL:Logtofile += "   => External Sharing: "+ $($site.SharingCapability) +" - Site Template Used: "+ $($site.Template) + $OFS
    $GLOBAL:Logtofile += "--------------------------------------------------------------------------------------------" + $OFS

    # ===> TO DO AND GET THE OFFICIAL SITE OWNER
    #Write-Host "   => Owner:", $site.Owner

    Check-All-SPOWebLists  -Url $site.Url -Credential $adminCreds -MyLogToFill

    $AllWebs = Get-SPOWebs -Url $site.Url -Credential $adminCreds
   
    foreach($MySPWeb in $AllWebs)
    {
        $GLOBAL:Logtofile += " ------------------------------------------------------------------------  " + $OFS
        $GLOBAL:Logtofile += "    => Subsite: "+ $($MySPWeb.Url) +" - Title: "+ $($MySPWeb.Title) + $OFS
        Write-Host "--------------------------------------------------------------------------------------------" -ForegroundColor yellow
        Write-Host "        ==>>", $MySPWeb.Title, "-", $MySPWeb.Url -ForegroundColor yellow
        Check-All-SPOWebLists  -Url $MySPWeb.Url -Credential $adminCreds -MyLogToFill
    }
    Write-Host "--------------------------------------------------------------------------------------------"
    $GLOBAL:Logtofile += " ------------------------------------------------------------------------  " + $OFS
}

$sw.Stop()

Write-host " ===================================================================================================" -ForegroundColor Green
write-host "     ===>>>>IRM Check and fix: ", $sw.Elapsed.ToString() -foreground Yellow
Write-host " ===================================================================================================" -ForegroundColor Green

$GLOBAL:Logtofile += " ===================================================================================================" + $OFS
$GLOBAL:Logtofile += "     ===>>>>IRM Check and fix: "+ $($sw.Elapsed.ToString()) + $OFS
$GLOBAL:Logtofile += " ===================================================================================================" + $OFS

if($GLOBAL:LogtoEmail -eq "")
{
    $GLOBAL:LogtoEmail += " There is no place where IRM is enable" + $OFS + $OFS
}

$GLOBAL:LogtoEmail += " ===================================================================================================" + $OFS
$GLOBAL:LogtoEmail += "  FIND THE DETAILS INTO THE LOG FILE AVAILABLE INTO THE SERVER FOLDER: "+ $DestinationLogFilePath + $OFS
$GLOBAL:LogtoEmail += " ===================================================================================================" + $OFS

add-content -Encoding UTF8 -Path $DestinationLogFilePath -Value $GLOBAL:Logtofile -Force

#Add the ZIP Action for the generated log file
$ZippedLogFilePath = $DestinationLogFilePath +".zip"
Compress-Archive -LiteralPath $DestinationLogFilePath -CompressionLevel Optimal -Update -Force -DestinationPath $ZippedLogFilePath

Send-MailMessage -From $EmailAddressFrom -to $EmailAddressToSend -Subject $EmailSubject -Body $GLOBAL:LogtoEmail -SmtpServer $EmailSMTPServer -port $EmailSMTPPort -Attachments $ZippedLogFilePath -Encoding $EmailencodingMail

Vous pouvez adapter et utiliser ce script à votre convenance.

Romelard Fabrice

Sites utilisés:

Version Anglaise:

Commentaires

Posts les plus consultés de ce blog

Série de vidéos sur le montage d'une serre horticole ACD

 Episode 1: Préparation du terrain Episode 2: Montage de la serre en elle même Episode 3: Finalisation avec le montage électrique alimentant la serre Bon visionnage Fab

Présentation des outils utiles pour l'entretien de ses haies vives

Afin de gérer les haies vives, il est nécessaire d'avoir recourt à un matériel adapté. Les solutions à batteries sont bien adaptées pour un usage personnel avec des dimensions raisonnables. Ainsi dans mon cas précis, j'utilise les outils suivants de la Gamme Ryobi 18V ONE+ électroportatif: Petit taille-haies simple mais efficace -  RYOBI OHT1855R Un modèle plus puissant qui fonctionne très bien -  RYOBI RY18HTX60A Pour les parties hautes de vos haies, voici un outil très utile -  RYOBI OPT1845 Enfin lorsque vous devez élaguer certains arbres ou certaines partie hautes de vos haies, ce dernier outil est très utile -  RYOBI OPP1820 Ces outils font parti maintenant de mon arsenal de base pour maintenir notre maison chaque saison de taille. Fab

Série de Videos sur Home Assistant intégrant la production Photovoltaïque

 Un certain nombre de vidéos sont en ligne pour intégrer sa production photovoltaïque dans Home Assistant en partant de la base. Installation de Home Assistant: On peut ensuite intégrer les composant des Micro-Onduleurs Enphase, mais aussi les batteries Enphase: Ou encore le composant de contrôle Ecojoko: Ce qui permet alors de faire des comparaisons entre les valeurs capturées: Des videos seront encore publiés dans les prochaines semaines sur différents aspects de cette solution. Fab