Documenting with PowerShell: Documenting Azure AD Settings

Almost all of my clients currently are running Office365 and AzureAD in some shape or form. I like having the ability to look at what exactly is going on in their Azure AD environment. Previously we’ve talked about documenting the office365 side. Today we’re going to be using the Azure AD module to create documentation for all of our clients.

The script currently documents the following:

  • The normal users in the Azure AD
  • All guest users in the Azure AD
  • All domain admins in the Azure AD
  • The Applications registered in the AzureAD. (This also helps in preventing OAuth2 fraud.)
  • The devices registered in the AzureAD.
  • all domains attached to the AzureAD.

As always I’ve created two scripts for this. One is for use with IT-Glue, the other your own documentation system. Both of them use the Secure App Model to connect to all your partner tenants and download the information. If you have issues with rate limiting, look at my earlier blog here.

IT-Glue version

This version of the script uses the primary domain to match to IT-Glue contacts, and then uploads it to the correct client. If the flexible asset does not exist, it creates it for you. ūüôā

########################## IT-Glue ############################
$APIKEy = "ITGlueKey"
$APIEndpoint = "https://api.eu.itglue.com"
$FlexAssetName = "Azure AD - AutoDoc v2"
$Description = "A network one-page document that shows the Azure AD settings."
########################## IT-Glue ############################

########################## Azure AD ###########################
$ApplicationId         = 'xxxx-xxxx-xxx-xxxx-xxxx'
$ApplicationSecret     = 'TheSecretTheSecret' | Convertto-SecureString -AsPlainText -Force
$TenantID              = 'YourTenantID'
$RefreshToken          = 'RefreshToken'
$ExchangeRefreshToken  = 'ExchangeRefreshToken'
$upn                   = 'UPN-Used-To-Generate-Tokens'
########################## Azure AD ###########################
#Grabbing ITGlue Module and installing.
If (Get-Module -ListAvailable -Name "ITGlueAPI") { 
    Import-module ITGlueAPI 
}
Else { 
    Install-Module ITGlueAPI -Force
    Import-Module ITGlueAPI
}
#Settings IT-Glue logon information
Add-ITGlueBaseURI -base_uri $APIEndpoint
Add-ITGlueAPIKey $APIKEy
 

#Connect to your Azure AD Account.
$credential = New-Object System.Management.Automation.PSCredential($ApplicationId, $ApplicationSecret)
$aadGraphToken = New-PartnerAccessToken -ApplicationId $ApplicationId -Credential $credential -RefreshToken $refreshToken -Scopes 'https://graph.windows.net/.default' -ServicePrincipal -Tenant $tenantID 
$graphToken = New-PartnerAccessToken -ApplicationId $ApplicationId -Credential $credential -RefreshToken $refreshToken -Scopes 'https://graph.microsoft.com/.default' -ServicePrincipal -Tenant $tenantID 
Connect-AzureAD -AadAccessToken $aadGraphToken.AccessToken -AccountId $UPN -MsAccessToken $graphToken.AccessToken -TenantId $tenantID | Out-Null
$Customers = Get-AzureADContract -All:$true
Disconnect-AzureAD
write-host "Checking if Flexible Asset exists in IT-Glue." -foregroundColor green
$FilterID = (Get-ITGlueFlexibleAssetTypes -filter_name $FlexAssetName).data
if (!$FilterID) { 
    write-host "Does not exist, creating new." -foregroundColor green
    $NewFlexAssetData = 
    @{
        type          = 'flexible-asset-types'
        attributes    = @{
            name        = $FlexAssetName
            icon        = 'sitemap'
            description = $description
        }
        relationships = @{
            "flexible-asset-fields" = @{
                data = @(
                    @{
                        type       = "flexible_asset_fields"
                        attributes = @{
                            order           = 1
                            name            = "Primary Domain Name"
                            kind            = "Text"
                            required        = $true
                            "show-in-list"  = $true
                            "use-for-title" = $true
                        }
                    },
                    @{
                        type       = "flexible_asset_fields"
                        attributes = @{
                            order          = 2
                            name           = "Users"
                            kind           = "Textbox"
                            required       = $false
                            "show-in-list" = $false
                        }
                    },
                    @{
                        type       = "flexible_asset_fields"
                        attributes = @{
                            order          = 3
                            name           = "Guest Users"
                            kind           = "Textbox"
                            required       = $false
                            "show-in-list" = $false
                        }
                    },
                    @{
                        type       = "flexible_asset_fields"
                        attributes = @{
                            order          = 4
                            name           = "Domain admins"
                            kind           = "Textbox"
                            required       = $false
                            "show-in-list" = $false
                        }
                    },
                    @{
                        type       = "flexible_asset_fields"
                        attributes = @{
                            order          = 5
                            name           = "Applications"
                            kind           = "Textbox"
                            required       = $false
                            "show-in-list" = $false
                        }
                    },
                    @{
                        type       = "flexible_asset_fields"
                        attributes = @{
                            order          = 6
                            name           = "Devices"
                            kind           = "Textbox"
                            required       = $false
                            "show-in-list" = $false
                        }
                    },
                    @{
                        type       = "flexible_asset_fields"
                        attributes = @{
                            order          = 7
                            name           = "Domains"
                            kind           = "Textbox"
                            required       = $false
                            "show-in-list" = $false
                        }
                    }
                )
            }
        }
    }
    New-ITGlueFlexibleAssetTypes -Data $NewFlexAssetData 
    $FilterID = (Get-ITGlueFlexibleAssetTypes -filter_name $FlexAssetName).data
}

#Grab all IT-Glue contacts to match the domain name.
write-host "Getting IT-Glue contact list" -foregroundColor green
$i = 0
do {
    $AllITGlueContacts += (Get-ITGlueContacts -page_size 1000 -page_number $i).data.attributes
    $i++
    Write-Host "Retrieved $($AllITGlueContacts.count) Contacts" -ForegroundColor Yellow
}while ($AllITGlueContacts.count % 1000 -eq 0 -and $AllITGlueContacts.count -ne 0) 



write-host "Start documentation process." -foregroundColor green

foreach ($Customer in $Customers) {
    $CustAadGraphToken = New-PartnerAccessToken -ApplicationId $ApplicationId -Credential $credential -RefreshToken $refreshToken -Scopes "https://graph.windows.net/.default" -ServicePrincipal -Tenant $customer.CustomerContextId
    $CustGraphToken = New-PartnerAccessToken -ApplicationId $ApplicationId -Credential $credential -RefreshToken $refreshToken -Scopes "https://graph.microsoft.com/.default" -ServicePrincipal -Tenant $customer.CustomerContextId
    write-host "Connecting to $($customer.Displayname)" -foregroundColor green
    Connect-AzureAD -AadAccessToken $CustAadGraphToken.AccessToken -AccountId $upn -MsAccessToken $CustGraphToken.AccessToken -TenantId $customer.CustomerContextId | out-null
    write-host "       Documenting Users for $($customer.Displayname)" -foregroundColor green
    $Users = Get-AzureADUser -All:$true
    write-host "       Documenting Applications for $($customer.Displayname)" -foregroundColor green
    $Applications = Get-AzureADApplication -All:$true
    write-host "       Documenting Devices for $($customer.Displayname)" -foregroundColor green
    $Devices = Get-AzureADDevice -all:$true
    write-host "       Documenting AzureAD Domains for $($customer.Displayname)" -foregroundColor green
    $customerdomains = get-azureaddomain
    $AdminUsers = Get-AzureADDirectoryRole | Where-Object { $_.Displayname -eq "Company Administrator" } | Get-AzureADDirectoryRoleMember
    $PrimaryDomain = ($customerdomains | Where-Object { $_.IsDefault -eq $true }).name
    Disconnect-AzureAD
    $TableHeader = "<table class=`"table table-bordered table-hover`" style=`"width:80%`">"
    $Whitespace = "<br/>"
    $TableStyling = "<th>", "<th style=`"background-color:#4CAF50`">"

    $NormalUsers = $users | Where-Object { $_.UserType -eq "Member" } | Select-Object DisplayName, mail,ProxyAddresses | ConvertTo-Html -Fragment | Out-String
    $NormalUsers = $TableHeader + ($NormalUsers -replace $TableStyling) + $Whitespace
    $GuestUsers = $users | Where-Object { $_.UserType -ne "Member" } | Select-Object DisplayName, mail | ConvertTo-Html -Fragment | Out-String
    $GuestUsers =  $TableHeader + ($GuestUsers -replace $TableStyling) + $Whitespace
    $AdminUsers = $AdminUsers | Select-Object Displayname, mail | ConvertTo-Html -Fragment | Out-String
    $AdminUsers = $TableHeader + ($AdminUsers  -replace $TableStyling) + $Whitespace
    $Devices = $Devices | select-object DisplayName, DeviceOSType, DEviceOSversion, ApproximateLastLogonTimeStamp | ConvertTo-Html -Fragment | Out-String
    $Devices =  $TableHeader + ($Devices -replace $TableStyling) + $Whitespace
    $HTMLDomains = $customerdomains | Select-Object Name, IsDefault, IsInitial, Isverified | ConvertTo-Html -Fragment | Out-String
    $HTMLDomains = $TableHeader + ($HTMLDomains -replace $TableStyling) + $Whitespace
    $Applications = $Applications | Select-Object Displayname, AvailableToOtherTenants,PublisherDomain | ConvertTo-Html -Fragment | Out-String
    $Applications = $TableHeader + ($Applications -replace $TableStyling) + $Whitespace
    


    $FlexAssetBody =
    @{
        type       = 'flexible-assets'
        attributes = @{
            traits = @{
                'primary-domain-name' = $PrimaryDomain
                'users'               = $NormalUsers
                'guest-users'         = $GuestUsers
                'domain-admins'       = $AdminUsers
                'applications'        = $Applications
                'devices'             = $Devices
                'domains'             = $HTMLDomains
            }
        }
    }

    Write-Host "          Finding $($customer.name) in IT-Glue" -ForegroundColor Green
    $orgID = @()
    foreach ($customerDomain in $customerdomains) {
        $orgID += ($AllITGlueContacts | Where-Object { $_.'contact-emails'.value -match $customerDomain.name }).'organization-id' | Select-Object -Unique
    }
    write-host "             Uploading Azure AD $($customer.name) into IT-Glue"  -ForegroundColor Green
    foreach ($org in $orgID) {
        $ExistingFlexAsset = (Get-ITGlueFlexibleAssets -filter_flexible_asset_type_id $($filterID.ID) -filter_organization_id $org).data | Where-Object { $_.attributes.traits.'primary-domain-name' -eq $PrimaryDomain }
        #If the Asset does not exist, we edit the body to be in the form of a new asset, if not, we just upload.
        if (!$ExistingFlexAsset) {
            $FlexAssetBody.attributes.add('organization-id', $org)
            $FlexAssetBody.attributes.add('flexible-asset-type-id', $($filterID.ID))
            write-host "                      Creating new Azure AD $($customer.name) into IT-Glue organisation $org" -ForegroundColor Green
            New-ITGlueFlexibleAssets -data $FlexAssetBody
        }
        else {
            write-host "                      Updating Azure AD $($customer.name) into IT-Glue organisation $org"  -ForegroundColor Green
            $ExistingFlexAsset = $ExistingFlexAsset[-1]
            Set-ITGlueFlexibleAssets -id $ExistingFlexAsset.id -data $FlexAssetBody
        }

    }

}

HTML version

The HTML version creates a file in C:\Temp for each of your Azure AD environments.

########################## Azure AD ###########################
$ApplicationId         = 'xxxx-xxxx-xxx-xxxx-xxxx'
$ApplicationSecret     = 'TheSecretTheSecret' | Convertto-SecureString -AsPlainText -Force
$TenantID              = 'YourTenantID'
$RefreshToken          = 'RefreshToken'
$ExchangeRefreshToken  = 'ExchangeRefreshToken'
$upn                   = 'UPN-Used-To-Generate-Tokens'
########################## Azure AD ###########################
#Connect to your Azure AD Account.
$credential = New-Object System.Management.Automation.PSCredential($ApplicationId, $ApplicationSecret)
$aadGraphToken = New-PartnerAccessToken -ApplicationId $ApplicationId -Credential $credential -RefreshToken $refreshToken -Scopes 'https://graph.windows.net/.default' -ServicePrincipal -Tenant $tenantID 
$graphToken = New-PartnerAccessToken -ApplicationId $ApplicationId -Credential $credential -RefreshToken $refreshToken -Scopes 'https://graph.microsoft.com/.default' -ServicePrincipal -Tenant $tenantID 
Connect-AzureAD -AadAccessToken $aadGraphToken.AccessToken -AccountId $UPN -MsAccessToken $graphToken.AccessToken -TenantId $tenantID | Out-Null
$Customers = Get-AzureADContract -All:$true
Disconnect-AzureAD
write-host "Start documentation process." -foregroundColor green

foreach ($Customer in $Customers) {
    $CustAadGraphToken = New-PartnerAccessToken -ApplicationId $ApplicationId -Credential $credential -RefreshToken $refreshToken -Scopes "https://graph.windows.net/.default" -ServicePrincipal -Tenant $customer.CustomerContextId
    $CustGraphToken = New-PartnerAccessToken -ApplicationId $ApplicationId -Credential $credential -RefreshToken $refreshToken -Scopes "https://graph.microsoft.com/.default" -ServicePrincipal -Tenant $customer.CustomerContextId
    write-host "Connecting to $($customer.Displayname)" -foregroundColor green
    Connect-AzureAD -AadAccessToken $CustAadGraphToken.AccessToken -AccountId $upn -MsAccessToken $CustGraphToken.AccessToken -TenantId $customer.CustomerContextId | out-null
    write-host "       Documenting Users for $($customer.Displayname)" -foregroundColor green
    $Users = Get-AzureADUser -All:$true
    write-host "       Documenting Applications for $($customer.Displayname)" -foregroundColor green
    $Applications = Get-AzureADApplication -All:$true
    write-host "       Documenting Devices for $($customer.Displayname)" -foregroundColor green
    $Devices = Get-AzureADDevice -all:$true
    write-host "       Documenting AzureAD Domains for $($customer.Displayname)" -foregroundColor green
    $customerdomains = get-azureaddomain
    $AdminUsers = Get-AzureADDirectoryRole | Where-Object { $_.Displayname -eq "Company Administrator" } | Get-AzureADDirectoryRoleMember
    $PrimaryDomain = ($customerdomains | Where-Object { $_.IsDefault -eq $true }).name
    Disconnect-AzureAD
    $TableHeader = "<table class=`"table table-bordered table-hover`" style=`"width:80%`">"
    $Whitespace = "<br/>"
    $TableStyling = "<th>", "<th style=`"background-color:#4CAF50`">"

    $NormalUsers = $users | Where-Object { $_.UserType -eq "Member" } | Select-Object DisplayName, mail,ProxyAddresses | ConvertTo-Html -PreContent "<h2>Users</h2>" -Fragment | Out-String
    $NormalUsers = $TableHeader + ($NormalUsers -replace $TableStyling) + $Whitespace
    $GuestUsers = $users | Where-Object { $_.UserType -ne "Member" } | Select-Object DisplayName, mail | ConvertTo-Html -PreContent "<h2>Guests</h2>" -Fragment | Out-String
    $GuestUsers =  $TableHeader + ($GuestUsers -replace $TableStyling) + $Whitespace
    $AdminUsers = $AdminUsers | Select-Object Displayname, mail | ConvertTo-Html -PreContent "<h2>Admins</h2>" -Fragment | Out-String
    $AdminUsers = $TableHeader + ($AdminUsers  -replace $TableStyling) + $Whitespace
    $Devices = $Devices | select-object DisplayName, DeviceOSType, DEviceOSversion, ApproximateLastLogonTimeStamp | ConvertTo-Html -PreContent "<h2>Devices</h2>" -Fragment | Out-String
    $Devices =  $TableHeader + ($Devices -replace $TableStyling) + $Whitespace
    $HTMLDomains = $customerdomains | Select-Object Name, IsDefault, IsInitial, Isverified | ConvertTo-Html -PreContent "<h2>Domains</h2>" -Fragment | Out-String
    $HTMLDomains = $TableHeader + ($HTMLDomains -replace $TableStyling) + $Whitespace
    $Applications = $Applications | Select-Object Displayname, AvailableToOtherTenants,PublisherDomain | ConvertTo-Html -PreContent "<h2>Applications</h2>" -Fragment | Out-String
    $Applications = $TableHeader + ($Applications -replace $TableStyling) + $Whitespace
    $head = @"
    <script>
    function myFunction() {
        const filter = document.querySelector('#myInput').value.toUpperCase();
        const trs = document.querySelectorAll('table tr:not(.header)');
        trs.forEach(tr => tr.style.display = [...tr.children].find(td => td.innerHTML.toUpperCase().includes(filter)) ? '' : 'none');
      }</script>
    <Title>Audit Log Report</Title>
    <style>
    body { background-color:#E5E4E2;
          font-family:Monospace;
          font-size:10pt; }
    td, th { border:0px solid black; 
            border-collapse:collapse;
            white-space:pre; }
    th { color:white;
        background-color:black; }
    table, tr, td, th {
         padding: 2px; 
         margin: 0px;
         white-space:pre; }
    tr:nth-child(odd) {background-color: lightgray}
    table { width:95%;margin-left:5px; margin-bottom:20px; }
    h2 {
    font-family:Tahoma;
    color:#6D7B8D;
    }
    .footer 
    { color:green; 
     margin-left:10px; 
     font-family:Tahoma;
     font-size:8pt;
     font-style:italic;
    }
    #myInput {
      background-image: url('https://www.w3schools.com/css/searchicon.png'); /* Add a search icon to input */
      background-position: 10px 12px; /* Position the search icon */
      background-repeat: no-repeat; /* Do not repeat the icon image */
      width: 50%; /* Full-width */
      font-size: 16px; /* Increase font-size */
      padding: 12px 20px 12px 40px; /* Add some padding */
      border: 1px solid #ddd; /* Add a grey border */
      margin-bottom: 12px; /* Add some space below the input */
    }
    </style>
"@
write-host "      Done - Creating HTML file for $($customer.Displayname)" -foregroundColor green
    $head, $NormalUsers,$GuestUsers,$AdminUsers,$Applications, $Devices,$HTMLDomains | Out-File "C:\temp\$($customer.displayname).html"
}

And that’s it! As always, Happy PowerShelling!

11 thoughts on “Documenting with PowerShell: Documenting Azure AD Settings

  1. David

    When I try to generate the customer tokens for connecting to AzureAD with
    $CustAadGraphToken = New-PartnerAccessToken -ApplicationId $ApplicationId -Credential $credential -RefreshToken $refreshToken -Scopes “https://graph.windows.net/.default” -ServicePrincipal -Tenant $customer.CustomerContextId
    $CustGraphToken = New-PartnerAccessToken -ApplicationId $ApplicationId -Credential $credential -RefreshToken $refreshToken -Scopes “https://graph.microsoft.com/.default” -ServicePrincipal -Tenant $customer.CustomerContextId

    I get errors saying:
    The user or administrator has not consented to use the application with ID ‘REDACTED’ named ‘REDACTED’. Send an interactive authorization request for this user and resource.

    Is this an issue with the permissions my application has been assigned?

    Reply
        1. David

          Update: After trying a few different environments, Re-running the Application creation script by saving it as a file and invoking it from a non-ISE session of powershell PSVersion 5.1.18362.628 running as local admin has been successful.
          Other environments gave the same output from the script but the app seems to be set up incorrectly.

          Reply
  2. Dave M

    Kelvin, thanks for another great share.
    I have 2 issues when running this, and any help is appreciated.

    1) Is it possible to tell it to skip certain tenants? We have certain tenants that we can’t access or document this way.

    2) Although the reports generate when using the HTML version, I get the below errors on line 31:

    Get-AzureADDirectoryRoleMember : Error occurred while executing GetAzureADDirectoryRoleMembers
    Code: Request_BadRequest
    Message: Syntax error at position 19 in ‘class DirectoryRole {
    DeletionTimestamp:
    ObjectId: c201c-494df
    ObjectType: Role
    Description: Can manage all aspects of Azure AD and Microsoft services that use Azure AD identities.
    DisplayName: Company Administrator
    IsSystem: True
    RoleDisabled: False
    RoleTemplateId: 62e90394145e10
    }
    ‘.
    RequestId: e3d-f735be
    DateTimeStamp: Sun, 24 May 2020 23:44:34 GMT
    HttpStatusCode: BadRequest
    HttpStatusDescription: Bad Request
    HttpResponseStatus: Completed
    At Documenting AAD Settings to HTML.ps1:31 char:108
    + … ayname -eq “Company Administrator” } | Get-AzureADDirectoryRoleMember
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : NotSpecified: (:) [Get-AzureADDirectoryRoleMember], ApiException
    + FullyQualifiedErrorId : Microsoft.Open.AzureAD16.Client.ApiException,Microsoft.Open.AzureAD16.PowerShell.GetAzureADDirectoryRoleMembers

    Reply
  3. Peter van der Linden

    Hi Kelvin,
    did you ever get this working as a Azure Function? Are there pitfalls to avoid?
    I’ve tried to implement a couple of your scripts as Triggered Powershell functions. Every time I run into errors directly after installing the ITGlueAPI which I placed in the subfolder Modules.
    Hope you have some advice how to approach this.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.