# Variables to connect to Entra ID $ClientId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" $TenantId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" $ClientSecret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" # Convert the client secret to a secure string $ClientSecretPass = ConvertTo-SecureString -String $ClientSecret -AsPlainText -Force # Create a credential object using the client ID and secure string $ClientSecretCredential = New-Object ` -TypeName System.Management.Automation.PSCredential ` -ArgumentList $ClientId, $ClientSecretPass # Connect to Microsoft Graph with Client Secret Connect-MgGraph -TenantId $TenantId -ClientSecretCredential $ClientSecretCredential # Days until expiration $DaysUntilExpiration = 30 $Now = Get-Date $Applications = Get-MgApplication -all $Logs = @() foreach ($App in $Applications) { $AppName = $App.DisplayName $AppID = $App.Id $ApplID = $App.AppId $AppCreds = Get-MgApplication -ApplicationId $AppID | Select-Object PasswordCredentials, KeyCredentials $Secrets = $AppCreds.PasswordCredentials $Certs = $AppCreds.KeyCredentials foreach ($Secret in $Secrets) { $StartDate = $Secret.StartDateTime $EndDate = $Secret.EndDateTime $SecretName = [string]$Secret.DisplayName $Owner = Get-MgApplicationOwner -ApplicationId $App.Id $Username = $Owner.AdditionalProperties.displayName $RemainingDaysCount = ($EndDate - $Now).Days if ($RemainingDaysCount -le $DaysUntilExpiration -and $RemainingDaysCount -ge 0) { $Logs += [PSCustomObject]@{ 'ApplicationName' = $AppName 'ApplicationID' = $ApplID 'Expiration Date' = $EndDate.ToString("dd/MM/yyyy HH:mm:ss") 'Owner' = [string]$Username } } } foreach ($Cert in $Certs) { $StartDate = $Cert.StartDateTime $EndDate = $Cert.EndDateTime $CertName = $Cert.DisplayName $Owner = Get-MgApplicationOwner -ApplicationId $App.Id $Username = $Owner.AdditionalProperties.displayName $RemainingDaysCount = ($EndDate - $Now).Days if ($RemainingDaysCount -le $DaysUntilExpiration -and $RemainingDaysCount -ge 0) { $Logs += [PSCustomObject]@{ 'ApplicationName' = $AppName 'ApplicationID' = $ApplID 'Expiration Date' = $EndDate.ToString("dd/MM/yyyy HH:mm:ss") 'Owner' = [string]$Username } } } } # Email details $sender = "xxxx@ccccc.com" $recipient = "xxxx@ccccc.com" $subject = "Service Principal expiring date report" $type = "HTML" $save = "false" # Html CSS style $Style = @" "@ $body = $Logs | ConvertTo-Html -Property 'ApplicationName','ApplicationID','Expiration Date','Owner' -PreContent "

Service Principal - Expira nos próximos $($DaysUntilExpiration) dias

" -Head $Style | Out-String $params = @{ Message = @{ Subject = $subject Body = @{ ContentType = $type Content = $body } ToRecipients = @( @{ EmailAddress = @{ Address = $recipient } } ) } SaveToSentItems = $save } # Send message Send-MgUserMail -UserId $sender -BodyParameter $params