Export Last Logon Time Report

Export Last Logon Time Report
This commit is contained in:
AdminDroid 2023-07-17 15:54:14 +05:30
parent 3378b5cc3d
commit d631236ae9

View File

@ -1,221 +1,309 @@
<# <#
============================================================================================= =============================================================================================
Name: Export Office 365 user last logon time report Name: Export Microsoft 365 users' last logon time report using PowerShell
Description: This script exports Office 365 users' last logon time CSV Version: 5.0
Version: 3.0 Last updated on: July, 2023
website: o365reports.com website: o365reports.com
Script by: O365Reports Team
For detailed Script execution: https://o365reports.com/2019/03/07/export-office-365-users-last-logon-time-csv/ Script Highlights:
~~~~~~~~~~~~~~~~~
#. Single script allows you to generate 10+ different last login reports.
#. The script can be executed with MFA enabled account too.
#. The script supports Certificate-based authentication (CBA).
#. Allows you get last login time report for list of users through import CSV.
#. You can generate report based on inactive days.
#. Result can be filtered based on user / all mailbox type.
#. Result can be filtered to lists never logged in mailbox alone.
#. Generate report for sign-in enabled users alone.
#. Supports filtering licensed users alone.
#. Gets login time report for admins alone
#. Export results to CSV file.
#. The assigned licenses column will show you the user-friendly-name like Office 365 Enterprise E3 rather than ENTERPRISEPACK.
#. Automatically installs Exchange Online PowerShell (to retrieve last logon time) and MS Graph PowerShell (to get license and admin roles) modules upon your confirmation.
For detailed Script execution: https://o365reports.com/2019/03/07/export-office-365-users-last-logon-time-csv/
============================================================================================ ============================================================================================
#> #>
#Accept input parameter
Param Param
( (
[Parameter(Mandatory = $false)] [string]$MBNamesFile,
[int]$InactiveDays, [int]$InactiveDays,
[switch]$UserMailboxOnly, [switch]$UserMailboxOnly,
[switch]$ReturnNeverLoggedInMB, [switch]$ReturnNeverLoggedInMB,
[string]$UserName, [switch]$SigninAllowedUsersOnly,
[string]$Password, [switch]$LicensedUsersOnly,
[switch]$MFA [switch]$AdminsOnly,
[string]$TenantId,
[string]$ClientId,
[string]$CertificateThumbprint
) )
Function ConnectModules
#Check for MSOnline module {
$Module=Get-Module -Name MSOnline -ListAvailable $MsGraphBetaModule = Get-Module Microsoft.Graph.Beta -ListAvailable
if($Module.count -eq 0) if($MsGraphBetaModule -eq $null)
{ {
Write-Host MSOnline module is not available -ForegroundColor yellow Write-host "Important: Microsoft Graph Beta module is unavailable. It is mandatory to have this module installed in the system to run the script successfully."
$Confirm= Read-Host Are you sure you want to install module? [Y] Yes [N] No $confirm = Read-Host Are you sure you want to install Microsoft Graph Beta module? [Y] Yes [N] No
if($Confirm -match "[yY]") if($confirm -match "[yY]")
{ {
Install-Module MSOnline Write-host "Installing Microsoft Graph Beta module..."
Import-Module MSOnline Install-Module Microsoft.Graph.Beta -Scope CurrentUser -AllowClobber
} Write-host "Microsoft Graph Beta module is installed in the machine successfully" -ForegroundColor Magenta
else }
{ else
Write-Host MSOnline module is required to connect AzureAD.Please install module using Install-Module MSOnline cmdlet. {
Exit Write-host "Exiting. `nNote: Microsoft Graph Beta module must be available in your system to run the script" -ForegroundColor Red
} Exit
} }
}
#Clear session $ExchangeOnlineModule = Get-Module ExchangeOnlineManagement -ListAvailable
Get-PSSession | Remove-PSSession if($ExchangeOnlineModule -eq $null)
{
#Get friendly name of license plan from external file Write-host "Important: Exchange Online module is unavailable. It is mandatory to have this module installed in the system to run the script successfully."
$FriendlyNameHash=Get-Content -Raw -Path .\LicenseFriendlyName.txt -ErrorAction Stop | ConvertFrom-StringData $confirm = Read-Host Are you sure you want to install Exchange Online module? [Y] Yes [N] No
if($confirm -match "[yY]")
{
#Set output file Write-host "Installing Exchange Online module..."
$ExportCSV=".\LastLogonTimeReport_$((Get-Date -format yyyy-MMM-dd-ddd` hh-mm` tt).ToString()).csv" Install-Module -Name ExchangeOnlineManagement -Scope CurrentUser
Write-host "Exchange Online Module is installed in the machine successfully" -ForegroundColor Magenta
#Check for EXO v2 module inatallation }
$Module = Get-Module ExchangeOnlineManagement -ListAvailable else
if($Module.count -eq 0) {
{ Write-host "Exiting. `nNote: Exchange Online module must be available in your system to run the script"
Write-Host Exchange Online PowerShell V2 module is not available -ForegroundColor yellow Exit
$Confirm= Read-Host Are you sure you want to install module? [Y] Yes [N] No }
if($Confirm -match "[yY]") }
{ Disconnect-MgGraph -ErrorAction SilentlyContinue | Out-Null
Write-host "Installing Exchange Online PowerShell module" Disconnect-ExchangeOnline -Confirm:$false
Install-Module ExchangeOnlineManagement -Repository PSGallery -AllowClobber -Force Write-Progress -Activity "Connecting modules(Microsoft Graph and Exchange Online module)..."
} try{
else if($TenantId -ne "" -and $ClientId -ne "" -and $CertificateThumbprint -ne "")
{ {
Write-Host EXO V2 module is required to connect Exchange Online.Please install module using Install-Module ExchangeOnlineManagement cmdlet. Connect-MgGraph -TenantId $TenantId -ClientId $ClientId -CertificateThumbprint $CertificateThumbprint -ErrorAction SilentlyContinue -ErrorVariable ConnectionError|Out-Null
Exit if($ConnectionError -ne $null)
} {
} Write-Host $ConnectionError -Foregroundcolor Red
Exit
#Connect Exchange Online with MFA }
if($MFA.IsPresent) $Scopes = (Get-MgContext).Scopes
{ if($Scopes -notcontains "Directory.Read.All" -and $Scopes -notcontains "Directory.ReadWrite.All")
Write-Host Connecting Exchange Online... {
Connect-ExchangeOnline | Out-Null Write-Host "Note: Your application required the following graph application permissions: Directory.Read.All" -ForegroundColor Yellow
Write-Host Connecting to Office 365... Exit
Connect-MsolService | Out-Null }
} Connect-ExchangeOnline -AppId $ClientId -CertificateThumbprint $CertificateThumbprint -Organization (Get-MgDomain | Where-Object {$_.isInitial}).Id -ShowBanner:$false
}
#Authentication using non-MFA else
else {
{ Connect-MgGraph -Scopes "Directory.Read.All" -ErrorAction SilentlyContinue -Errorvariable ConnectionError |Out-Null
#Storing credential in script for scheduling purpose/ Passing credential as parameter if($ConnectionError -ne $null)
if(($UserName -ne "") -and ($Password -ne "")) {
{ Write-Host $ConnectionError -Foregroundcolor Red
$SecuredPassword = ConvertTo-SecureString -AsPlainText $Password -Force Exit
$Credential = New-Object System.Management.Automation.PSCredential $UserName,$SecuredPassword }
} Connect-ExchangeOnline -UserPrincipalName (Get-MgContext).Account -ShowBanner:$false
else }
{ }
$Credential=Get-Credential -Credential $null catch
} {
Write-Host Connecting Exchange Online... Write-Host $_.Exception.message -ForegroundColor Red
Connect-ExchangeOnline -Credential $Credential Exit
Write-Host Connecting to Office 365... }
Connect-MsolService -Credential $Credential Write-Host "Microsoft Graph Beta Powershell module is connected successfully" -ForegroundColor Green
} Write-Host "Exchange Online module is connected successfully" -ForegroundColor Green
}
$Result="" Function CloseConnection
$Output=@() {
$MBUserCount=0 Disconnect-MgGraph|Out-Null
$OutputCount=0 Disconnect-ExchangeOnline -Confirm:$false
}
Function ProcessMailBox
Get-Mailbox -ResultSize Unlimited | Where{$_.DisplayName -notlike "Discovery Search Mailbox"} | ForEach-Object{ {
$upn=$_.UserPrincipalName Write-Progress -Activity "`n Processing mailbox: $Script:MailBoxUserCount - $DisplayName"
$CreationTime=$_.WhenCreated $Script:MailBoxUserCount++
$LastLogonTime=(Get-MailboxStatistics -Identity $upn).lastlogontime if($AccountEnabled -eq $True)
$DisplayName=$_.DisplayName {
$MBType=$_.RecipientTypeDetails $SigninStatus = "Allowed"
$Print=1 }
$MBUserCount++ else
$RolesAssigned="" {
Write-Progress -Activity "`n Processed mailbox count: $MBUserCount "`n" Currently Processing: $DisplayName" $SigninStatus = "Blocked"
#Retrieve lastlogon time and then calculate Inactive days
if($LastLogonTime -eq $null)
{
$LastLogonTime ="Never Logged In"
$InactiveDaysOfUser="-"
}
else
{
$InactiveDaysOfUser= (New-TimeSpan -Start $LastLogonTime).Days
}
#Get licenses assigned to mailboxes
$User=(Get-MsolUser -UserPrincipalName $upn)
$Licenses=$User.Licenses.AccountSkuId
$AssignedLicense=""
$Count=0
#Convert license plan to friendly name
foreach($License in $Licenses)
{
$Count++
$LicenseItem= $License -Split ":" | Select-Object -Last 1
$EasyName=$FriendlyNameHash[$LicenseItem]
if(!($EasyName))
{$NamePrint=$LicenseItem}
else
{$NamePrint=$EasyName}
$AssignedLicense=$AssignedLicense+$NamePrint
if($count -lt $licenses.count)
{
$AssignedLicense=$AssignedLicense+","
} }
}
if($Licenses.count -eq 0)
{
$AssignedLicense="No License Assigned"
}
#Inactive days based filter #Retrieve lastlogon time and then calculate Inactive days
if($InactiveDaysOfUser -ne "-"){ if($LastLogonTime -eq $null)
if(($InactiveDays -ne "") -and ([int]$InactiveDays -gt $InactiveDaysOfUser)) {
{ $LastLogonTime = "Never Logged In"
$Print=0 $InactiveDaysOfUser = "-"
}} }
else
{
$InactiveDaysOfUser = (New-TimeSpan -Start $LastLogonTime).Days
}
#License assigned based filter #Get licenses assigned to mailboxes
if(($UserMailboxOnly.IsPresent) -and ($MBType -ne "UserMailbox")) $Licenses = (Get-MgBetaUserLicenseDetail -UserId $UPN).SkuPartNumber
{ $AssignedLicense = @()
$Print=0 #Convert license plan to friendly name
} if($Licenses.count -eq 0)
{
#Never Logged In user $AssignedLicense = "No License Assigned"
if(($ReturnNeverLoggedInMB.IsPresent) -and ($LastLogonTime -ne "Never Logged In")) }
{ else
$Print=0 {
} foreach($License in $Licenses)
{
#Get roles assigned to user $EasyName = $FriendlyNameHash[$License]
$Roles=(Get-MsolUserRole -UserPrincipalName $upn).Name if(!($EasyName))
if($Roles.count -eq 0) {$NamePrint = $License}
{ else
$RolesAssigned="No roles" {$NamePrint = $EasyName}
} $AssignedLicense += $NamePrint
else }
{ }
foreach($Role in $Roles) #Inactive days based filter
{ if($InactiveDaysOfUser -ne "-")
$RolesAssigned=$RolesAssigned+$Role {
if($Roles.indexof($role) -lt (($Roles.count)-1)) if(($InactiveDays -ne "") -and ($InactiveDays -gt $InactiveDaysOfUser))
{ {
$RolesAssigned=$RolesAssigned+"," return
} }
} }
} #UserMailboxOnly
if(($UserMailboxOnly.IsPresent) -and ($MailBoxType -ne "UserMailbox"))
#Export result to CSV file {
if($Print -eq 1) return
{ }
$OutputCount++ #Never Logged In user
$Result=@{'UserPrincipalName'=$upn;'DisplayName'=$DisplayName;'LastLogonTime'=$LastLogonTime;'CreationTime'=$CreationTime;'InactiveDays'=$InactiveDaysOfUser;'MailboxType'=$MBType; 'AssignedLicenses'=$AssignedLicense;'Roles'=$RolesAssigned} if(($ReturnNeverLoggedInMB.IsPresent) -and ($LastLogonTime -ne "Never Logged In"))
$Output= New-Object PSObject -Property $Result {
$Output | Select-Object UserPrincipalName,DisplayName,LastLogonTime,CreationTime,InactiveDays,MailboxType,AssignedLicenses,Roles | Export-Csv -Path $ExportCSV -Notype -Append return
} }
#Signin Allowed Users
if($SigninAllowedUsersOnly.IsPresent -and $AccountEnabled -eq $False)
{
return
}
#Licensed Users ony
if($LicensedUsersOnly -and $Licenses.Count -eq 0)
{
return
}
#Get roles assigned to user
$Roles = @()
$Roles = Get-MgBetaUserTransitiveMemberOf -UserId $UPN |Select-Object -ExpandProperty AdditionalProperties
$Roles=$Roles|?{$_.'@odata.type' -eq '#microsoft.graph.directoryRole'}
if($Roles.count -eq 0)
{
$RolesAssigned = "No roles"
}
else
{
$RolesAssigned = @($Roles.displayName) -join ','
}
#Admins only
if($AdminsOnly.IsPresent -and $RolesAssigned -eq 'No roles')
{
return
}
#Export result to CSV file
$Script:OutputCount++
$Result = [PSCustomObject]@{'UserPrincipalName'=$UPN;'DisplayName'=$DisplayName;'SigninStatus' = $SigninStatus ;'LastLogonTime'=$LastLogonTime;'CreationTime'=$_.WhenCreated;'InactiveDays'=$InactiveDaysOfUser;'MailboxType'=$MailBoxType; 'AssignedLicenses'=(@($AssignedLicense)-join ',');'Roles'=$RolesAssigned}
$Result | Export-Csv -Path $ExportCSV -Notype -Append
} }
#Get friendly name of license plan from external file
try{
$FriendlyNameHash = Get-Content -Raw -Path .\LicenseFriendlyName.txt -ErrorAction SilentlyContinue -ErrorVariable FileError | ConvertFrom-StringData
if($FileError -ne $null)
{
Write-Host $FileError -ForegroundColor Red
Exit
}
}
catch
{
Write-Host $_.Exception.Message -ForegroundColor Red
Exit
}
#Module functions
ConnectModules
Write-Host "`nNote: If you encounter module related conflicts, run the script in a fresh PowerShell window." -ForegroundColor Yellow
#Set output file
$ExportCSV = ".\LastLogonTimeReport_$((Get-Date -format yyyy-MMM-dd-ddd` hh-mm-ss` tt).ToString()).csv"
$MailBoxUserCount = 1
$OutputCount = 0
#Check for input file
if([string]$MBNamesFile -ne "")
{
#We have an input file, read it into memory
$Mailboxes = @()
try{
$InputFile = Import-Csv -Path $MBNamesFile -Header "MBIdentity"
}
catch
{
Write-Host $_.Exception.Message -ForegroundColor Red
CloseConnection
Exit
}
Foreach($item in $InputFile.MBIdentity)
{
$Mailbox = Get-ExoMailBox -Identity $item -PropertySets All -ErrorAction SilentlyContinue
if($Mailbox -ne $null)
{
$DisplayName = $Mailbox.DisplayName
$UPN = $Mailbox.UserPrincipalName
$LastLogonTime = (Get-ExoMailboxStatistics -Identity $UPN -Properties LastLogonTime).LastLogonTime
$MailBoxType = $Mailbox.RecipientTypeDetails
$CreatedDateTime = $Mailbox.WhenCreated
$AccountEnabled = (Get-MgBetaUser -UserId $UPN).AccountEnabled
ProcessMailBox
}
else
{
Write-Host $item not found -ForegroundColor Red
}
}
}
#Get all mailboxes from Office 365
else
{
Get-ExoMailbox -ResultSize Unlimited -PropertySets All | Where{$_.DisplayName -notlike "Discovery Search Mailbox"} | ForEach-Object {
$DisplayName = $_.DisplayName
$UPN = $_.UserPrincipalName
$LastLogonTime = (Get-ExoMailboxStatistics -Identity $UPN -Properties LastLogonTime).LastLogonTime
$MailBoxType = $_.RecipientTypeDetails
$CreatedDateTime = $_.WhenCreated
$AccountEnabled = (Get-MgBetaUser -UserId $UPN).AccountEnabled
ProcessMailBox
}
}
#Open output file after execution #Open output file after execution
Write-Host `nScript executed successfully Write-Host `nScript executed successfully
if((Test-Path -Path $ExportCSV) -eq "True") if((Test-Path -Path $ExportCSV) -eq "True")
{ {
Write-Host "Detailed report available in: $ExportCSV" Write-Host "Exported report has " -NoNewline
Write-Host "$OutputCount mailboxe(s)" -ForegroundColor Green
Write-Host Exported report has $OutputCount mailboxes $Prompt = New-Object -ComObject wscript.shell
$Prompt = New-Object -ComObject wscript.shell $UserInput = $Prompt.popup("Do you want to open output file?",` 0,"Open Output File",4)
$UserInput = $Prompt.popup("Do you want to open output file?",` if ($UserInput -eq 6)
0,"Open Output File",4) {
If ($UserInput -eq 6) Invoke-Item "$ExportCSV"
{ }
Invoke-Item "$ExportCSV" Write-Host `n "The Output file availble in:" -NoNewline -ForegroundColor Yellow; Write-Host "$ExportCSV" `n
}
} }
Else else
{ {
Write-Host No mailbox found Write-Host "No mailbox found" -ForegroundColor Red
} }
#Clean up session Write-Host `n~~ Script prepared by AdminDroid Community ~~`n -ForegroundColor Green
Get-PSSession | Remove-PSSession Write-Host "~~ Check out " -NoNewline -ForegroundColor Green; Write-Host "admindroid.com" -ForegroundColor Yellow -NoNewline; Write-Host " to get access to 1800+ Microsoft 365 reports. ~~" -ForegroundColor Green `n`n
CloseConnection