Skip to main content

Notify license shortage with automation

<shortdescription>

Use case


Teams webhook notification


PowerShell script


$tenantId=Get-AutomationVariable -Name "<nameoftenantidrunbookvariable>"
$ClientId=Get-AutomationVariable -Name "<nameofclientidrunbookvariable>"
$CredentialObject=Get-AutomationPSCredential -Name '<nameofclientsecretrunbookcredentials>'
$ClientSecret = $CredentialObject.GetNetworkcredential().password

$WebhookURI = ""
$PercentageAlert = "98"

$Body = @{
"tenant" = $TenantId
"client_id" = $ClientId
"scope" = "https://graph.microsoft.com/.default"
"client_secret" = $ClientSecret
"grant_type" = "client_credentials"
}

$Params = @{
"Uri" = "https://login.microsoftonline.com/$TenantId/oauth2/v2.0/token"
"Method" = "Post"
"Body" = $Body
"ContentType" = "application/x-www-form-urlencoded"
}

$AuthResponse = Invoke-RestMethod @Params

$Header = @{
    "Authorization" = "Bearer $($AuthResponse.access_token)"
}

$AllLicenses = Invoke-RestMethod -Method GET -Uri "https://graph.microsoft.com/v1.0/subscribedSkus" -Header $Header

Foreach($License in $AllLicenses.value){
    if($License.prepaidUnits.enabled -ge 50){
        try{
            $LicensePercentage = ($License.consumedUnits/$License.prepaidUnits.enabled*100)
        }
        catch{
            $null
        }
        if($LicensePercentage -ge $PercentageAlert){
            $CurrentTime = Get-Date
$JsonBody = @"
{
    "@context": "https://schema.org/extensions",
    "@type": "MessageCard",
    "themeColor": "880808",
    "title": "License warning: $($License.skuPartNumber)",
    "text": "License has more than 98% allocations. Please order new licenses in order not to jeopardize the operation.<br><br>Licensename: $($License.skuPartNumber) <br><br>Licenses available: $($License.prepaidUnits.enabled - $License.consumedUnits) <br><br> Licenses total: $($License.prepaidUnits.enabled) <br> Licenses assigned: $($License.consumedUnits) <br><br> Time of the evaluation: $($CurrentTime.addHours(2))<br><br> More details about the license: https://admin.microsoft.com/#/licensedetailpage/$($License.skuId)",
  }
"@

            Invoke-RestMethod -Method Post -Body $JsonBody -Uri $WebhookURI
        }
    }
}