Skip to content

Shadow AI and Cloud Discovery Report

directorcia edited this page Nov 30, 2026 · 1 revision

This document describes ai-shadow-report.ps1, a read-only Microsoft Graph report that inventories discovered cloud applications, identifies possible AI use, exports app and user associations, and creates an interactive HTML dashboard.

The script is designed for Windows PowerShell 5.1 and PowerShell 7.

Summary

The script:

  1. Loads built-in and optional AI application detection rules.
  2. Authenticates to Microsoft Graph with the CloudApp-Discovery.Read.All delegated scope.
  3. Lists all accessible Cloud Discovery streams or a requested stream.
  4. Queries aggregated discovered-app data for a 7-, 30-, or 90-day period.
  5. Classifies apps by name, domain, Defender for Cloud Apps category, and AI keyword rules.
  6. Optionally queries app-to-user associations.
  7. Writes an app CSV, a user CSV, and a self-contained HTML report.
  8. Opens the HTML report in the default browser unless -NoLaunch is used.

The script uses the Microsoft Graph beta Cloud Discovery API. Beta API behavior and fields can change.

Prerequisites

PowerShell

  • Windows PowerShell 5.1 or PowerShell 7.
  • #requires -Version 5.1 is enforced at the top of the script.

Microsoft Graph PowerShell SDK

The following commands must be available:

  • Connect-MgGraph
  • Invoke-MgGraphRequest
  • Get-MgContext
  • Disconnect-MgGraph

Install the authentication module when it is not already available:

Install-Module Microsoft.Graph.Authentication -Scope CurrentUser

The Graph SDK package can be used in a tenant that has the required delegated permissions.

Permissions and tenant access

The script requests:

CloudApp-Discovery.Read.All

An administrator must grant tenant consent for this permission. The signed-in account also needs access to the Cloud Discovery data and discovery streams being queried.

Discovery data

At least one populated Cloud Discovery stream must be accessible. The script does not generate or import discovery data itself.

Only data available from the selected streams and period is returned. Transfer byte fields can be blank when the source data does not provide volume information.

Quick start

From the repository directory:

.\ai-shadow-report.ps1

The default operation:

  • Uses a 30-day lookback.
  • Uses all accessible discovery streams.
  • Exports all discovered apps.
  • Queries app-user associations for exported apps.
  • Uses ai-apps-catalog.json beside the script when available.
  • Writes reports beside the script.
  • Opens the HTML report automatically.

Common examples:

# AI-only app export
.\ai-shadow-report.ps1 -Days 30 -AiOnly

# Refresh and cache the AI catalog
.\ai-shadow-report.ps1 -UpdateCatalog

# Query users only for AI-classified apps
.\ai-shadow-report.ps1 -AiUsersOnly

# Skip user association queries
.\ai-shadow-report.ps1 -SkipUsers

# Generate reports for one stream without opening them
.\ai-shadow-report.ps1 -Days 90 -StreamId "00000000-0000-0000-0000-000000000000" -NoLaunch

# Write to a specific directory and return a summary object
$result = .\ai-shadow-report.ps1 -OutputDirectory "C:\Reports\ShadowAI" -PassThru
$result

# Preview the operation under -WhatIf
.\ai-shadow-report.ps1 -WhatIf

# Run in US Government cloud
.\ai-shadow-report.ps1 -Environment USGov -NoLaunch

Parameters

Parameter Type Default Description
-Days 7, 30, or 90 30 Cloud Discovery lookback period.
-StreamId String No value Processes only the matching discovery stream ID. If omitted, all accessible streams are processed.
-TenantId String Existing context or interactive selection Tenant ID or tenant domain used during Graph authentication.
-Environment Global, USGov, USGovDoD Global Microsoft Graph sovereign cloud environment.
-OutputDirectory String Script directory Existing directory that receives the generated report files. The directory is validated and must exist.
-CatalogPath String ai-apps-catalog.json beside the script AI catalog JSON file used for local detection rules.
-UpdateCatalog Switch Off Downloads the catalog before report collection and caches it when writable.
-CatalogUri HTTPS URL Repository ai-apps-catalog.json URL HTTPS source used with -UpdateCatalog.
-AiOnly Switch Off Exports only Known AI-capable and Possible AI product matches. Per-app user queries are also skipped for non-AI apps.
-AiUsersOnly Switch Off Exports all discovered apps but queries app-user associations only for AI-classified apps.
-SkipUsers Switch Off Skips app-user queries. The user CSV is emitted with its header only.
-NoLaunch Switch Off Saves the HTML report without opening it in the default browser.
-PassThru Switch Off Emits a structured summary object after successful collection.

AiOnly, AiUsersOnly, and SkipUsers change collection scope but do not change which discovery data is used.

Filtering behavior

The switches are independent and should be read as follows:

Default

All discovered apps are exported. User lookups are attempted for exported apps whose stream exposes user information and whose reported app user count is not zero.

-AiOnly

Only apps classified as:

  • Known AI-capable product
  • Possible AI product

are exported. Non-AI apps are excluded from both app and user outputs.

-AiUsersOnly

All discovered apps remain in the app CSV and HTML report. User lookups run only for AI-classified apps.

-SkipUsers

All app collection and report generation continue, but no app-user endpoints are queried. The user CSV contains only the header row.

Execution flow

The script has four visible stages.

Stage 1: Load the AI catalog

Catalog selection is resolved in this order when refresh is requested:

  1. Download and parse the catalog from -CatalogUri.
  2. Cache the downloaded JSON to -CatalogPath if the path is writable.
  3. Fall back to the local catalog if the download or JSON conversion fails.
  4. Fall back to the embedded built-in catalog if the local catalog is missing or unreadable.

Without -UpdateCatalog, the script loads -CatalogPath when present and otherwise uses the built-in catalog.

The catalog implementation:

  • Requires a products array with product and pattern fields.
  • Supports an optional keywordPattern field.
  • Compiles and validates regular expressions.
  • Replaces matching built-in product entries by product name.
  • Adds new products to the built-in rules.
  • Merges the catalog with embedded known cloud domains.
  • Does not treat catalog entries as proof of use; they are matching evidence.

A custom catalog entry can override a built-in product rule. For example:

{
  "version": "custom-2026",
  "products": [
    {
      "product": "Example AI",
      "pattern": "\\bexample[ ._-]*ai\\b"
    }
  ],
  "keywordPattern": "(?i)\\b(generative ai|large language model|llm)\\b"
}

Stage 2: Authenticate

The script checks for an existing Microsoft Graph context:

  • The tenant matches -TenantId, if supplied.
  • The Graph environment matches.
  • The context contains CloudApp-Discovery.Read.All.

An eligible context is reused. Otherwise, the script calls Connect-MgGraph with:

  • Scopes = CloudApp-Discovery.Read.All
  • Environment = <selected environment>
  • TenantId = <tenant ID or domain, if supplied>
  • NoWelcome = $true

The Graph endpoints are:

Environment Graph root
Global https://graph.microsoft.com
USGov https://graph.microsoft.us
USGovDoD https://dod-graph.microsoft.us

When the script creates a new session, it disconnects from Microsoft Graph in finally. Reused sessions remain open.

Stage 3: Collect discovery data

The script queries the uploaded-stream collection:

/beta/security/dataDiscovery/cloudAppDiscovery/uploadedStreams

When -StreamId is specified, it filters the returned stream list. An unknown or inaccessible stream causes the run to fail with a message containing available stream IDs.

For each stream, it queries:

/beta/security/dataDiscovery/cloudAppDiscovery/uploadedStreams/{streamId}/
microsoft.graph.security.aggregatedAppsDetails(period=duration'P{Days}D')

Graph collection responses are paginated through @odata.nextLink. Pagination URLs must use HTTPS on the active Graph host and port 443. Repeated pagination URLs stop the collection rather than looping.

Graph requests include:

Prefer: include-unknown-enum-members

Transient HTTP 429, 500, 502, 503, or 504 responses are retried up to four attempts. Retry delay is taken from Retry-After when available, capped between 1 and 120 seconds, and otherwise uses exponential backoff.

AI classification

Each app is classified using available app name, domains, and category values.

Known AI-capable product

This confidence level is assigned when:

  • An app name or domain matches a product regex or known AI domain.
  • The Defender category exactly matches an AI category.

Recognized Defender AI categories include:

  • generativeAi
  • aiModelProvider
  • mcpServer
  • clientAiApp
  • Display-name equivalents containing the corresponding names

Known matches also carry a product name or product list. Category-only matches use the app name as the product display value.

Possible AI product

This confidence level is assigned when the catalog keyword regex matches the app name or a domain and no known-product match has been found.

No AI match

This is assigned when no catalog, known-domain, Defender category, or keyword match is found.

Classification unavailable

This can appear only when no catalog object is supplied by the internal code path. Normal script execution loads a built-in catalog even if external catalog files fail.

Known catalog and domain matches are intended for investigation. They do not prove that an organization approved the app or that a person used an AI feature.

App data

The app CSV and HTML dashboard contain these fields:

Field Meaning
StreamId Source discovery stream ID.
StreamName Stream display name.
LogDataProvider Source log provider.
LastDataReceivedDateTime Last data timestamp reported by the stream.
AnonymizeUserData Stream anonymization setting.
PeriodDays Report lookback period.
AppId Graph discovered-app ID.
AppName Discovered-app name.
Domains Domains associated with the app.
AiConfidence Known, possible, no match, or unavailable classification.
AiProducts Product names inferred from catalog or domain matches.
AiEvidence Reason for the classification.
Category Defender for Cloud Apps category.
SanctionStatus Sanctioned, Unsanctioned, Monitored, or Not tagged extracted from tags.
Tags All non-empty app tags.
RiskScore Defender risk score when available.
UploadBytes Aggregate upload bytes reported by the source.
DownloadBytes Aggregate download bytes reported by the source.
TotalBytes Upload plus download where either field is numeric.
TransactionCount Source transaction count.
UserCount Graph-reported app user count.
IpAddressCount Graph-reported IP address count.
LastSeenDateTime Last-seen timestamp.
SupportedTrafficTypes Traffic types declared by the stream.

Traffic totals are app and stream aggregates for the selected period, not per-user totals. Do not divide app totals across users or sum overlapping streams.

User association collection

For an exported app, the script determines whether to query users using these rules:

  • -SkipUsers skips all lookups.
  • Streams without a userName supported entity type skip lookups.
  • -AiUsersOnly skips non-AI apps.
  • -AiOnly skips non-AI apps.
  • Apps with a parsed UserCount of zero are skipped.

Eligible apps are queried through:

/beta/security/dataDiscovery/cloudAppDiscovery/uploadedStreams/{streamId}/
microsoft.graph.security.aggregatedAppsDetails(period=duration'P{Days}D')/
{appId}/users

HTTP 401 or 403 responses stop the run. Other per-app user lookup failures are recorded as warnings and collection continues.

The user CSV contains:

Field Meaning
StreamId Source stream ID.
StreamName Source stream name.
AnonymizeUserData Stream anonymization setting.
PeriodDays Lookback period.
AppId Graph app ID.
AppName App name.
AiConfidence App AI classification.
AiProducts Classified product names.
Category Defender app category.
SanctionStatus App sanction status.
RiskScore App risk score.
UserIdentifier Identifier returned by Graph.

User data can contain personal or sensitive tenant information and should be protected consistently with the organization's data-handling policy.

Output files

Reports use a millisecond timestamp to avoid simple name collisions:

shadow-it-apps-yyyyMMdd-HHmmss-fff.csv
shadow-it-users-yyyyMMdd-HHmmss-fff.csv
shadow-it-report-yyyyMMdd-HHmmss-fff.html

The app and user CSV files are staged with temporary random names and moved to their final names only after all three reports are generated. The script refuses to overwrite an existing destination file.

On a partially failed run, temporary files and any already-published reports are cleaned up. Existing reports are not overwritten.

CSV encoding and formula safety

  • Windows PowerShell 5.1 writes UTF-8.
  • PowerShell 7 writes UTF-8 BOM.
  • Empty result sets are exported with a header-only CSV.
  • Values beginning with spreadsheet formula characters are prefixed with an apostrophe: =, +, -, @, leading tabs, or leading line breaks.
  • Embedded line breaks are replaced with spaces.

HTML report

The HTML report is offline and self-contained; it has no external dependencies.

It includes:

  • Tenant, environment, period, and catalog metadata.
  • Exported app, known AI, possible AI, unsanctioned AI, user association, and stream counts.
  • A discovered-app table.
  • Search and confidence/sanction/stream filters.
  • Sortable app and user tables.
  • Numeric sorting for risk, users, upload, download, and total bytes.
  • Visible app-row CSV and JSON downloads.
  • Print/save-to-PDF support.
  • Light/dark theme switching.
  • Stream coverage and operational warnings.
  • A notice explaining stream overlap and app-level traffic limitations.

The HTML user table displays at most 500 associations. The user CSV remains the complete association export unless collection failed or was skipped.

-PassThru output

With -PassThru, the script emits a PSCustomObject containing:

Property Description
AppReportPath App CSV path.
UserReportPath User CSV path.
HtmlReportPath HTML report path.
TenantId Active tenant ID.
Environment Selected Graph environment.
PeriodDays Lookback period.
StreamCount Processed stream count.
TotalDiscoveredApps Total apps returned before filtering.
ExportedAppCount Exported app-row count.
KnownAiAppCount Known AI-capable app rows.
PossibleAiAppCount Possible AI app rows.
UnsanctionedAiCount Unsanctioned app rows with an AI match.
UserAssociationCount Exported app-user association count.
CatalogVersion Active catalog version or fallback version.
CatalogSource Catalog source description.
Warnings Operational warning list.

Example:

$result = .\ai-shadow-report.ps1 -NoLaunch -PassThru
[PSCustomObject]@{
    KnownAI = $result.KnownAiAppCount
    PossibleAI = $result.PossibleAiAppCount
    Warnings = $result.Warnings.Count
    Report = $result.HtmlReportPath
}

-WhatIf and -Confirm

The script supports SupportsShouldProcess.

-WhatIf prevents the Graph connection and report export action. -Confirm can ask for confirmation before collection begins.

Example:

.\ai-shadow-report.ps1 -WhatIf -Confirm

Debugging

Run with -Debug to expose:

  • Resolved report directory.
  • Selected Graph root and environment.
  • Graph session reuse or connection decisions.
  • Catalog source and rule count.
  • Stream and app counts.
  • Graph collection pagination URLs and errors.
  • Stage timing.
  • Temporary file cleanup.
  • Published report names.

Example:

.\ai-shadow-report.ps1 -Days 30 -Debug

In interactive Windows PowerShell 5.1, the script changes a DebugPreference of Inquire to Continue to avoid debug prompt crashes.

Troubleshooting

Microsoft.Graph.Authentication is missing

Install the authentication module:

Install-Module Microsoft.Graph.Authentication -Scope CurrentUser

Open a new PowerShell session and confirm:

Get-Command Connect-MgGraph, Invoke-MgGraphRequest, Get-MgContext, Disconnect-MgGraph

Insufficient permissions or 403 responses

Verify that:

  • CloudApp-Discovery.Read.All has tenant consent.
  • The signed-in account has access to Defender for Cloud Apps discovery data.
  • The account can access the selected stream.

Authentication 401/403 failures stop app or user collection where the script cannot safely continue.

No streams returned

Confirm that:

  • Defender for Cloud Apps discovery is configured.
  • Log or device discovery data has been uploaded.
  • The signed-in account can view the streams.
  • The selected environment is correct.

Stream ID not found

Run without -StreamId to list available stream IDs and names. Debug output and the stream preview include the available stream scope.

Catalog download failed

The script falls back to the local JSON catalog and then the embedded catalog. Warnings are included in console output and the HTML report.

To diagnose a catalog:

{
  "version": "example",
  "products": [
    { "product": "Example AI", "pattern": "\\bexample ai\\b" }
  ],
  "keywordPattern": "(?i)\\b(generative ai|llm)\\b"
}

Ensure the JSON is valid and every pattern is a valid .NET regular expression.

Empty app CSV

An empty app CSV can mean:

  • No apps were discovered in the selected period.
  • -AiOnly filtered out every app.
  • The stream contains no usable app records.

The script still writes the header-only CSV and HTML report.

Empty user CSV

The user CSV can be empty because:

  • -SkipUsers was used.
  • The stream does not expose userName.
  • The app UserCount values are zero.
  • -AiUsersOnly or -AiOnly excluded the apps.
  • Graph returned no user associations.

Per-app lookup failures are reported as warnings rather than stopping the remaining run.

Browser did not open

Use -NoLaunch to suppress the launch attempt. If launch is enabled, a warning is recorded if Start-Process fails. The HTML report path is still printed to the console.

Operational considerations

  • The report is read-only and does not sanction, unsanction, block, or change applications.
  • Multiple discovery streams can overlap. Do not sum app traffic across streams.
  • App totals are not user-level evidence.
  • AI classification is heuristic and can produce false positives or false negatives.
  • The Graph beta API is not guaranteed to preserve field names or behavior.
  • A signed-in user may see only data permitted by tenant and Defender roles.
  • Reports can contain tenant IDs, app names, domains, user identifiers, IP usage counts, and traffic data.
  • Store reports according to the organization's privacy, audit, and data-retention requirements.
  • In air-gapped environments, avoid -UpdateCatalog; the built-in catalog and an optional local catalog remain available.

Clone this wiki locally