<#	
	.NOTES
	===========================================================================
	 Created on:	15/07/2021
	 Created by:   	Mathieu Ait Azzouzene
	 Organization: 	Experteam
	 Version:		1.0
	 Script Name:	Get-MFAUsersReport   	
	===========================================================================
	.SYNOPSYS
	.DESCRIPTION
	This script:
    - Adds MFA registered users to an Azure AD group for Conditional Access purpose
    - Creates a snapshot csv report of MFA registered/not registered users
    - Feeds an execution history log files (MFAUsersReport.log)
#>
$Name = 'MFAUsersReport'
$LogPath = Split-Path ($MyInvocation.MyCommand.Path) -Parent
$LogfileName = "$Name" + '.log'

$Date = Get-Date -Format "yyyyddMM_HH.mm"
$GroupObjectID = '87316f25-5fc3-4db7-8e40-65959a90b67f'

<#	
	Functions Declaration
#>
Function Write-Log
{
<#	
	.NOTES
	===========================================================================
	 Created on:	31/07/2018
	 Created by:   	Mathieu Ait Azzouzene
	 Organization: 	Experteam Corp
	 Version:		1.1
	 Function Name:	Write-Log     	
	===========================================================================
	.DESCRIPTION
	This script add logs to a file using the CMTrace format.
	.PARAMETER	Message
	The message to add to the log file.
	.PARAMETER	LogFile
	The full log file path.
	.PARAMETER	Severity
	1 - INFORMATION
	2 - WARNING
	3 - ERROR
	.PARAMETER	Component
	Any string, the component parameter is FYI.	
	.EXAMPLES
	Write-Log -Message "INFORMATION" -severity 1 -component 'Main'			 		   
	Write-Log -Message "WARNING" -severity 2 -component 'Main'						   
	Write-Log -Message "ERROR" -severity 3 -component 'Main'
#>
[CmdletBinding()]
    PARAM(
		 [Parameter(Mandatory=$True,Position=0,HelpMessage='Enter a message to add to the log file.')]
         [String]$Message,
         [String]$Logfile = "$LogPath\$LogfileName",
		 [ValidateSet(1,2,3)]
         [int]$severity = 1,
         [string]$component = 'Main'
         )
 
         $TimeZoneBias = Get-WmiObject -Query "Select Bias from Win32_TimeZone"
         $Date1= Get-Date -Format "HH:mm:ss.fff"
         $Date2= Get-Date -Format "MM-dd-yyyy"
 
         "<![LOG[$Message]LOG]!><time=$([char]34)$date1$($TimeZoneBias.bias)$([char]34) date=$([char]34)$date2$([char]34) component=$([char]34)$component$([char]34) context=$([char]34)$([char]34) type=$([char]34)$severity$([char]34) thread=$([char]34)$([char]34) file=$([char]34)$([char]34)>"| Out-File -FilePath $Logfile -Append -NoClobber -Encoding default
}

Function Start-Log
{
Write-Log 'Script execution started.' -severity 1 -component "Start-Log"
}

Function Stop-Log
{
Write-Log 'Script execution ended.' -severity 1 -component "Stop-Log"
}

Start-Log

try
{
    Get-MsolDomain -ErrorAction Stop > $null
}
catch 
{
    Write-Host "Connecting to Microsoft Online Service..."
    Connect-MsolService
}

#Get MFA registered users Azure AD group members
$GroupMembers = (Get-MsolGroupMember -GroupObjectId $GroupObjectID -All).ForEach('ObjectId')

#Get all users
$AllUsers = get-msoluser -All | where {$_.UserType -eq "Member"}

#Get users who has registered for MFA
$RegisteredUsers = $AllUsers | Where-Object {$_.StrongAuthenticationMethods}

#Get users who has not registered for MFA
$NotRegisteredUsers = $AllUsers | Where-Object {$_.StrongAuthenticationMethods.Count -eq 0}

#Add registered users to MFA registered users Azure AD group
ForEach ($User in $RegisteredUsers)
{
    if($User.ObjectId -notin $GroupMembers)
    {
        Write-Host "Adding $($User.displayname) to group"
        Write-Log "Adding $($User.displayname) to group"
        Add-MsolGroupMember -groupobjectid $GroupObjectID -groupmembertype 'user' -groupmemberobjectid $User.objectid
    }
}

#Remove not registered users from MFA registered users Azure AD group
ForEach ($User in $NotRegisteredUsers)
{
    if($User.ObjectId -in $GroupMembers)
    {
        Write-Host "Removing $($User.displayname) from group"
        Write-Log "Removing $($User.displayname) from group"
        Remove-MsolGroupMember -groupobjectid $GroupObjectID -groupmembertype 'user' -groupmemberobjectid $User.objectid
    }
}

#Create a CSV report
Write-Host "Exporting result to $Logpath"
Write-Log "Exporting result to $Logpath"
$AllUsers |`
Select-Object UserPrincipalName,Usertype,objectid,@{N='MFA Status';E={if ($_.StrongAuthenticationMethods){"Registered"} else {"Not Registered"}}} |`
Export-Csv -NoClobber -NoTypeInformation -Force -delimiter ',' -Path "$LogPath\$Name $date.csv"

Stop-Log