Understanding and managing risky user activities is crucial for maintaining the security of your Azure AD environment. Identifying potential threats early allows for prompt action to protect your organization's resources. In this article, we will explore a PowerShell script that automates the retrieval and display of risky user status using Microsoft Graph API.
Script Overview
The script is designed to connect to Microsoft Graph and retrieve information about users deemed "risky" by Azure AD. The script organizes this information into a structured format, making it easier for administrators to review and act upon.
Here is the script:
<#
.SYNOPSIS
Get-RiskyUserStatus.ps1
.DESCRIPTION
Retrieve and display the risky user status from Microsoft Graph.
#>
# Import necessary modules
Import-Module -Name 'Microsoft.Graph'
Import-Module -Name 'Microsoft.Graph.Beta.Identity.SignIns'
# Define constants
$TenantId = "" # Azure AD Tenant ID
$ClientId = "" # Application (client) ID
$ClientSecret = "" # Client secret
# Convert Client Secret to Secure String
$SecureClientSecret = ConvertTo-SecureString $ClientSecret -AsPlainText -Force
# Create credential object
$Credential = New-Object System.Management.Automation.PSCredential($ClientId, $SecureClientSecret)
# Acquire a token
$Token = Get-MsalToken -ClientId $ClientId -TenantId $TenantId -ClientSecret $SecureClientSecret -Scopes https://graph.microsoft.com/.default
# Convert token to secure string
$SecureToken = ConvertTo-SecureString $Token.AccessToken -AsPlainText -Force
# Connect to Microsoft Graph
Connect-MgGraph -AccessToken $SecureToken
# Retrieve the risky users
$riskyUsers = Get-MgRiskyUser
# Create result object
$result = $riskyUsers | ForEach-Object {
[PSCustomObject]@{
Id = $_.Id
IsDeleted = $_.IsDeleted
IsProcessing = $_.IsProcessing
RiskLevel = $_.RiskLevel
RiskState = $_.RiskState
RiskDetail = $_.RiskDetail
RiskLastUpdatedDateTime = $_.RiskLastUpdatedDateTime
UserDisplayName = $_.UserDisplayName
UserPrincipalName = $_.UserPrincipalName
}
}
# Convert result to JSON format
echo "</report>"
$result | ConvertTo-Json -Compress
echo "</report>"