SKYPE Policy Compliance Script

Now a days, I am working on automating various parts of Office 365 for different environments.

Sharing a script requested by one of SKYPE for Business Administrator to apply External access policy and Client Policy for all users in the environment.

Here are the requirements:

  • Any Skype Online user where ClientPolicy is null apply the custom Client policy.
  • Any Skype Online users where ExternalAccessPolicy is null or FederationAndPICDefault –> apply custom federation policy.

Download and extract the Script Solution Zip file from below link and update the following:

https://github.com/VikasSukhija/Downloads/blob/master/SKOBCompliancePolicy.zip

Update the Variables Section of SkobCompliancePolicy.ps1

####################Variables/Logs###########################

$log1 = Write-Log -Name “Skype-PolicyCompliance” -folder “logs” -Ext “log”
$log2 = Write-Log -Name “Skype-PolicyComplianceSummary” -folder “logs” -Ext “log”
$Report1 = Write-Log -Name “Skype-PolicyComplianceClient” -folder “Report” -Ext “csv”
$Report2 = Write-Log -Name “Skype-PolicyComplianceExternal” -folder “Report” -Ext “csv”
$Domain = “organization.onmicrosoft.com” # update the tenant
$smtpserver = “smtpserver”   # Smtp server for relay
$email1 = “VikasS@labtest.com”   # update email addresses and from address
$erroremail = “ReportsLogs@labtest.com”
$from = “DoNotReply@labtest.com”
$count = “100”                                                # Count to check if number of users that we have to apply policy are more than 100, this can be increased or                                                                              # decreased as per your requirements, on first iteration increase it to higher than you can set it to whatever   
                     #suits your organization.
$policy1 = “CustomClientPolicy”     # Client Policy
$policy2 = “Customfederationonly”   # External access policy
$collection1 = @()
$collection2 = @()
########################Start main script#######################

 

under main script section:

$user1 = “lab-test-svc@labtest.com” #update as per account you will use

 

Now run the encrypt.bat file and enter the password of the service account from which you will schedule/run the script(make sure you are doing it from that service account session only)

 

 

Next step is to run the SkobCompliancePolicy.bat file or schedule it.
Logs will be stored inside the logs folder and reports of success/failures will be sent on email as well as stored in report folder.
Logs and Reports retention is set to 60 days which you can change as well by updating $limit = (Get-Date).AddDays(-60) #for report recycle at the end of the script.

 

 

PowerShell Code:
<#     
    .NOTES 
    =========================================================================== 
    Created with:     ISE 
    Created on:       8/09/2018  
    Created by:       Vikas Sukhija (http://SysCloudPro.com) 
    Organization:      
    Filename:         SkobCompliancePolicy.ps1 
    =========================================================================== 
    .DESCRIPTION 
    This Script will Apply Skype Complaince Policies 
#> 
$error.clear() 
try { $null = Stop-Transcript } 
catch { $error.clear() } 
#########################Load Modules and functions################# 
function LaunchSOL 
{ 
  param 
  ( 
    $Domain, 
    $UserCredential 
  ) 
     
  Write-Host -Object "Enter Skype Online Credentials" -ForegroundColor Green 
  $CSSession = New-CsOnlineSession -Credential $UserCredential -OverrideAdminDomain $Domain -Verbose 
  Import-PSSession -Session $CSSession -Prefix "SOL" 
  return $UserCredential 
} 
Function RemoveSOL 
{ 
  $Session = Get-PSSession | Where-Object -FilterScript { $_.ComputerName -like "admin1a.online.lync.com" } 
  Remove-PSSession $Session 
} 
 
function Write-Log 
{ 
  [CmdletBinding()] 
  param 
  ( 
    [Parameter(Mandatory = $true,ParameterSetName = 'Create')] 
    [array]$Name, 
    [Parameter(Mandatory = $true,ParameterSetName = 'Create')] 
    [string]$Ext, 
    [Parameter(Mandatory = $true,ParameterSetName = 'Create')] 
    [string]$folder, 
     
    [Parameter(ParameterSetName = 'Create',Position = 0)][switch]$Create, 
     
    [Parameter(Mandatory = $true,ParameterSetName = 'Message')] 
    [String]$Message, 
    [Parameter(Mandatory = $true,ParameterSetName = 'Message')] 
    [String]$path, 
    [Parameter(Mandatory = $false,ParameterSetName = 'Message')] 
    [ValidateSet('Information','Warning','Error')] 
    [string]$Severity = 'Information', 
     
    [Parameter(ParameterSetName = 'Message',Position = 0)][Switch]$MSG 
  ) 
  switch ($PsCmdlet.ParameterSetName) { 
    "Create"{ 
      $log = @() 
      $date1 = Get-Date -Format d 
      $date1 = $date1.ToString().Replace("/""-") 
      $time = Get-Date -Format t 
     
      $time = $time.ToString().Replace(":""-") 
      $time = $time.ToString().Replace(" """) 
     
      foreach ($n in $Name) 
      {$log += (Get-Location).Path + "\" + $folder + "\" + $n + "_" + $date1 + "_" + $time + "_.$Ext"} 
      return $log 
    } 
    "Message"{ 
      $date = Get-Date 
      $concatmessage = "|$date" + "|   |" + $Message +"|  |" + "$Severity|" 
      switch($Severity){ 
        "Information"{Write-Host -Object $concatmessage -ForegroundColor Green} 
        "Warning"{Write-Host -Object $concatmessage -ForegroundColor Yellow} 
        "Error"{Write-Host -Object $concatmessage -ForegroundColor Red} 
      } 
       
      Add-Content -Path $path -Value $concatmessage 
    } 
  } 
} 
  
####################Variables/Logs########################### 
$log1 = Write-Log -Name "Skype-PolicyCompliance" -folder "logs" -Ext "log" 
$log2 = Write-Log -Name "Skype-PolicyComplianceSummary" -folder "logs" -Ext "log" 
$Report1 = Write-Log -Name "Skype-PolicyComplianceClient" -folder "Report" -Ext "csv" 
$Report2 = Write-Log -Name "Skype-PolicyComplianceExternal" -folder "Report" -Ext "csv" 
 
$Domain = "organization.onmicrosoft.com" 
$smtpserver = "smtpserver" 
$email1 = "VikasS@labtest.com" 
$erroremail = "ReportsLogs@labtest.com" 
$from = "DoNotReply@labtest.com" 
$count = "100" 
 
 
$policy1 = "CustomClientPolicy" 
$policy2 = "Customfederationonly" 
 
$collection1 = @() 
$collection2 = @() 
########################Start main script####################### 
Start-Transcript -Path $log1 
Write-Log  -Message "Script Started" -path $log2 
try 
{ 
  $encrypted1 = Get-Content -Path .\password1.txt 
  $user1 = "lab-test-svc@labtest.com" #update as per account you will use 
  $password1 = ConvertTo-SecureString -String $encrypted1 
  $Credential1 = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $user1$password1 
  LaunchSOL -Domain $Domain -allowclobber -UserCredential $Credential1 
} 
catch 
{ 
  $_.Exception 
  Write-Host -Object "Exception has occured in connecting to SKOB" -ForegroundColor Yellow 
  break; 
} 
 
############################Fetch all users that have Client policy Set to Null###################### 
try 
{ 
  Write-Log -Message "Start fetching allskobclientpolicynull" -path $log2 
  $allskobclientpolicynull = Get-SOLCsOnlineUser -Filter { (OnPremHostingProvider -eq 'sipfed.online.lync.com'-and (ClientPolicy -eq $null-and (DirSyncEnabled -eq 'True')} -resultsize:unlimited | Select-Object -Property UserprincipalName, ClientPolicy, UserAccountControl 
  $allskobclientpolicynull  = $allskobclientpolicynull | Where-Object -FilterScript {$_.UserAccountControl -notlike "*AccountDisabled*"} 
   
  Write-Log -Message "Finished fetching allskobclientpolicynull" -path $log2 
} 
catch{ 
  $_.Exception 
  Write-Log -Message "Exception has occured fetching allskobclientpolicynull" -path $log2 
  Send-MailMessage -SmtpServer $smtpserver -To $email1 -Bcc $erroremail -From $from -Subject "Exception has occured fetching allskobclientpolicynull" 
  break; 
} 
 
if(($allskobclientpolicynull.count -gt "0"-and ($allskobclientpolicynull.count -le $count)){ 
  $allskobclientpolicynull | ForEach-Object -Process { 
    $error.clear() 
    $mcoll = "" | Select-Object -Property userprincipalname, Status 
    $upn = $_.userprincipalname 
    Write-Log -Message "Processing ...... $upn" -path $log2 
    $mcoll.userprincipalname = $upn 
    Grant-SolCsClientPolicy -Identity $upn -PolicyName $policy1 
    if($error){$mcoll.Status = "Error" 
      Write-Log -Message "Processing ...... $upn" -path $log2 -Severity Warning 
    } 
    else{ 
      $mcoll.Status = "ClientPolicyApplied" 
       
    } 
    $collection1 +$mcoll 
  } 
  $collection1 | Export-Csv $Report1 -NoTypeInformation 
  Send-MailMessage -SmtpServer $smtpserver -From $from -To $email1 -Bcc $erroremail -Subject "Report - Skype Client Compliance Policy" -Body "Report - Skype Client Compliance Policy" -Attachments $Report1 
}elseif($allskobclientpolicynull.count -gt $count){ 
  Write-Log -Message "Count of user policy is greater than $count for allskobclientpolicynull" -path $log2 -Severity Warning 
  Send-MailMessage -SmtpServer $smtpserver -To $email1 -Bcc $erroremail -From $from -Subject "Count of user policy is greater than $count for allskobclientpolicynull" 
} 
 
############################Fetch all users that have External access policy Set to Null or default###################### 
try 
{ 
  Write-Log -Message "Start fetching allskobexternalpolicynullordefault" -path $log2 
  $allskobexternalpolicynullordefault = Get-SOLCsOnlineUser -Filter { (OnPremHostingProvider -eq 'sipfed.online.lync.com'-and (DirSyncEnabled -eq 'True'-and ((ExternalAccessPolicy -eq $null-or (ExternalAccessPolicy -eq 'FederationAndPICDefault'))} -resultsize:unlimited | Select-Object -Property UserprincipalName, ExternalAccessPolicy, UserAccountControl 
  $allskobexternalpolicynullordefault  = $allskobexternalpolicynullordefault | Where-Object -FilterScript {$_.UserAccountControl -notlike "*AccountDisabled*"} 
   
  Write-Log -Message "Finished fetching allskobexternalpolicynullordefault" -path $log2 
} 
catch{ 
  $_.Exception 
  Write-Log -Message "Exception has occured fetching allskobexternalpolicynullordefault" -path $log2 
  Send-MailMessage -SmtpServer $smtpserver -To $email1 -Bcc $erroremail -From $from -Subject "Exception has occured fetching allskobexternalpolicynullordefault" 
  break; 
} 
 
if(($allskobexternalpolicynullordefault.count -gt "0"-and ($allskobexternalpolicynullordefault.count -le $count)){ 
  $allskobexternalpolicynullordefault| ForEach-Object -Process { 
    $error.clear() 
    $mcoll = "" | Select-Object -Property userprincipalname, Status 
    $upn = $_.userprincipalname 
    Write-Log -Message "Processing ...... $upn" -path $log2 
    $mcoll.userprincipalname = $upn 
    Grant-SolCsExternalAccessPolicy -Identity $upn -PolicyName $policy2 
    if($error){$mcoll.Status = "Error" 
      Write-Log -Message "Processing ...... $upn" -path $log2 -Severity Warning 
    } 
    else{ 
      $mcoll.Status = "ExternalAccessPolicyApplied" 
    } 
    $collection2 +$mcoll 
  } 
 
  $collection2 | Export-Csv $Report2 -NoTypeInformation 
  Send-MailMessage -SmtpServer $smtpserver -From $from -To $email1 -Bcc $erroremail -Subject "Report - Skype External Compliance Policy" -Body "Report - Skype External Compliance Policy" -Attachments $Report2 
} 
elseif($allskobexternalpolicynullordefault.count -gt $count){ 
    Write-Log -Message "Count of user policy is greater than $count for allskobexternalpolicynullordefault" -path $log2 -Severity Warning 
    Send-MailMessage -SmtpServer $smtpserver -To $email1 -Bcc $erroremail -From $from -Subject "Count of user policy is greater than $count for allskobexternalpolicynullordefault" 
  } 
RemoveSOL 
########################Recycle reports & logs############## 
$path1 = ".\report\" 
$path2 = ".\Logs\" 
$limit = (Get-Date).AddDays(-60) #for report recycling 
Get-ChildItem -Path $path1 | 
Where-Object -FilterScript {$_.CreationTime -lt $limit| 
Remove-Item -Recurse -Force 
 
Get-ChildItem -Path $path2 | 
Where-Object -FilterScript {$_.CreationTime -lt $limit| 
Remove-Item -Recurse -Force 
 
Write-Log  -Message "Script finished" -path $log2 
Stop-Transcript 
Send-MailMessage -SmtpServer $smtpserver -From $from -To $erroremail -Subject "Transcript Log - Skype Compliance Policy" -Body "Transcript Log - Skype Compliance Policy" -Attachments $log1 
################################################################################

 

Thanks for reading and downloading
Sukhija Vikas

2 thoughts on “SKYPE Policy Compliance Script

  1. Pingback: SKYPE Policy Compliance Script | Cloud Computers Guide

  2. Pingback: What Broke after Teams Module Upgrade to version 4 ? | Tech Wizard

Leave a comment