This script connects to Microsoft Graph using the scopes `'Application.ReadWrite.All'` and `'AuditLog.Read.All'`, retrieves all applications in the tenant, and checks the status of each application’s credentials (passwords and certificates). It determines whether these credentials are valid by comparing their expiration dates to the current date. The script also retrieves the application's owner details and checks for any recent sign-in activity. All the information is logged into a custom object, including details like secret and certificate validity, owner, and last sign-in date.
Here is the script:
Connect-MgGraph -Scopes 'Application.ReadWrite.All','AuditLog.Read.All'
$Messages = @{
DurationNotice = @{
Info = @(
'The operation is running and will take longer the more applications the tenant has...'
'Please wait...'
) -join ' '
}
}
Write-Host $Messages.DurationNotice.Info -ForegroundColor yellow
$Applications = Get-MgApplication -All
$Logs = @()
foreach ($App in $Applications) {
$AppName = $App.DisplayName
$AppID = $App.Id
$ApplID = $App.AppId
Write-Output "Getting $AppName Data..."
$AppCreds = $Applications | Where-Object Id -EQ $AppID |
Select-Object PasswordCredentials, KeyCredentials
$now = Get-Date
# Secret validation
$SecretValid = $false
$Secrets = $AppCreds.PasswordCredentials
if ($Secrets) {
$SecretEndDate = $Secrets | Sort-Object EndDateTime -Descending -Top 1 | Select-Object -ExpandProperty EndDateTime
if($SecretEndDate -gt $now){
$SecretValid = $true
}
}
# Certificate validation
$CertValid = $false
$Certs = $AppCreds.KeyCredentials
if($Certs){
$CertEndDate = $Certs | Sort-Object EndDateTime -Descending -Top 1 | Select-Object -ExpandProperty EndDateTime
if ($CertEndDate -gt $now) {
$CertValid = $true
}
}
# Get Owner
Write-Output "Getting Owner Info"
$Owner = Get-MgApplicationOwner -ApplicationId $App.Id
$Username = $Owner.AdditionalProperties.userPrincipalName -join ';'
$OwnerID = $Owner.Id -join ';'
if ($null -eq $Owner.AdditionalProperties.userPrincipalName) {
$Username = @(
$Owner.AdditionalProperties.displayName
'**<This is an Application>**'
) -join ' '
}
if ($null -eq $Owner.AdditionalProperties.displayName) {
$Username = '<<No Owner>>'
}
Write-Output "Getting SignIn Info"
$Signin = $false
$SigninDate = Get-MgAuditLogSignIn -Filter "appId eq '$ApplID'" -Top 1 | Select-Object -ExpandProperty CreatedDateTime
if($SigninDate){
$Signin = $true
}
############################################
$Logs += [PSCustomObject]@{
'ApplicationName' = $AppName
'ApplicationID' = $ApplID
'Secret Valid' = $SecretValid
'Secret End Date' = $SecretEndDate
'Certificate Valid' = $CertValid
'Certificate End Date' = $CertEndDate
'Owner' = $Username
'Owner_ObjectID' = $OwnerID
'Signin Present' = $Signin
'Last Sign-In Date' = $SigninDate
}
############################################
}
$Logs