Automating with Graph API

Automating with Graph API

Last week we discussed sending emails with Graph API. You can read about it here. Today we will be taking that script and making it so it can be automated. On the backend, you will need to create an Azure App. You can read about how to do that here. The following code only works in Powershell 7 and above. Automating with Graph API works best in PowerShell 7. You will need to set up your App with Users.Read.All and Mail.Send as the minimal. levels.

The Script

import-module Microsoft.Graph.Users
Import-module Microsoft.Graph.Users.Actions  

$EmailToSend = "A Cloud Email @ your domain"
$EmailToReceive = "Any Email"
$AppID = "This is your App ID"
$SecuredPassword = "This is your Password"
$tenantID = "This is your tenant ID"

$SecuredPasswordPassword = ConvertTo-SecureString -String $SecuredPassword -AsPlainText -Force
$ClientSecretCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $AppID, $SecuredPasswordPassword

Connect-MgGraph -TenantId $tenantID -ClientSecretCredential $ClientSecretCredential

#Connect-MgGraph -Scopes "User.Read.All, Mail.Send"
$users = Get-MgUser -filter "accountenabled eq false"
$ReturnString = ""
foreach ($user in $users) {
    if ($null -ne (Get-MgUserLicenseDetail -UserId $user.Id)) {
        [pscustomobject][ordered]@{
            UPN      = $user.UserPrincipalName
            Licenses = (Get-MgUserLicenseDetail -UserId $user.id).SkuPartNumber -join ", "
        }
        $ReturnString = $ReturnString + "$($user.UserPrincipalName): $((Get-MgUserLicenseDetail -UserId $user.id).SkuPartNumber -join ", ")`n"
    }
}
 
$body = @"
<html>
<header>Licenses</header>
<body>
<center>
<h1>Disabled Users</h1>
<h2>With Licenses</h2>
</center>
$ReturnString
</body>
</html>
"@
$params = @{
    message = @{
        subject = "Disabled Users with Licenses"
        body = @{
            contentType = "HTML"
            content = $body
        }
        toRecipients = @(
            @{
                emailAddress = @{
                    address = $EmailToReceive 
                }
            }
        )
    }
    saveToSentItems = "false"
}
 
# A UPN can also be used as -UserId.
Send-MgUserMail -UserId $EmailToSend -BodyParameter $params

The Breakdown

This script is the same as last week’s except for how it connects and how you feed the email addresses. We are using the Client Secret Credential flag, which is only available in Powershell 7, to trigger the connect command. You need some basic information first. This information will allow Automating with Graph API to work.

$AppID = "This is your App ID"
$SecuredPassword = "This is your Password"
$tenantID = "This is your tenant ID"

The App is the application ID from the azure app you created. the tenant ID is also the tenant ID of the azure app you created. Remember, I stated to keep the secret key value. This is where you will use it. Place it in the Secure Password area. Next, we need to convert this information into a secure object.

$SecuredPasswordPassword = ConvertTo-SecureString -String $SecuredPassword -AsPlainText -Force
$ClientSecretCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $AppID, $SecuredPasswordPassword

Now, we need to convert the plain text to a secure string. We do this with the convertto-securestring command. We enter the string and force it with the force tag. Once we have done that, we want to create a credential object. We use the new-object command to create an automation pscredential object. We feed it the appID and the password we created above. This gives us the ps object that we will use for the next part.

Connect-MgGraph -TenantId $tenantID -ClientSecretCredential $ClientSecretCredential

Using the connect-mggraph command we connect to our tenant and pass the app id and password as a single object. This will connect us directly to Graph API. Later we will run this script through the task scheduler. The remainder of the script will stay the same. Finally, we supply the email addresses. Automating with Graph API couldn’t be easier. So Enjoy!

Additional Links

Emails with Graph API

Emails with Graph API

Last week we spoke about finding disabled users with licensing using PowerShell and graph API. Today, we will be expanding from that blog. We are going to send the results ourselves. Next week, we will create this into an automation using application rights and azure apps. However, today we will send Emails with Graph API and Powershell.

The Script

import-module Microsoft.Graph.Users
Import-module Microsoft.Graph.Users.Actions  

Connect-MgGraph -Scopes "User.Read.All, Mail.Send"
$users = Get-MgUser -filter "accountenabled eq false"
$ReturnString = ""
foreach ($user in $users) {
    if ($null -ne (Get-MgUserLicenseDetail -UserId $user.Id)) {
        [pscustomobject][ordered]@{
            UPN      = $user.UserPrincipalName
            Licenses = (Get-MgUserLicenseDetail -UserId $user.id).SkuPartNumber -join ", "
        }
        $ReturnString = $ReturnString + "$($user.UserPrincipalName): $((Get-MgUserLicenseDetail -UserId $user.id).SkuPartNumber -join ", ")`n"
    }
}

$EmailSend = Read-Host "Email Address to send (Cloud Only)"
$Emailreceive = Read-Host "Email Address to Receive"

$body = @"
<html>
<header>Licenses</header>
<body>
<center>
<h1>Disabled Users</h1>
<h2>With Licenses</h2>
</center>
$ReturnString
</body>
</html>
"@
$params = @{
    message = @{
        subject = "Disabled Users with Licenses"
        body = @{
            contentType = "HTML"
            content = $body
        }
        toRecipients = @(
            @{
                emailAddress = @{
                    address = $Emailreceive
                }
            }
        )
    }
    saveToSentItems = "false"
}

# A UPN can also be used as -UserId.
Send-MgUserMail -UserId $EmailSend -BodyParameter $params

The Breakdown

The same

Like last week, we are using the Microsoft Graph PowerShell module. The first part of this code is the same as last week. So you can take a good read on that one. The only difference is our scope. We are adding mail.send. Mail.Send allows us to send emails from cloud users. It will not work with inactive, soft-deleted, or on-premise-hosted devices. Thus the connect-mggraph will look like the below

Connect-MgGraph -Scopes "User.Read.All, Mail.Send"

The only other thing we have added to the original script is a return string. We initialize the return string with a $returnstring = “” and then we build the string out. Using the same as before, we grab the SKU part number. Finally, we use the join. The difference is we wrap the command in a bubble, $(), for our string. Then we put the sting, the new information, and a line break, `n, into the string.

$ReturnString = $ReturnString + "$($user.UserPrincipalName): $((Get-MgUserLicenseDetail -UserId $user.id).SkuPartNumber -join ", ")`n"

Emails with Graph API

The first thing we want to know is Who we are sending the email to and Who is sending the email. The one sending the email has limitations. First, it can’t be an inactive user. The user can’t be in a soft-deleted state. Finally, it has to be hosted in the cloud. The person we are sending to has to have an email box.

The next part is where we create the email we are going to send. Remember that returnstring we made a few moments ago, it’s time to use that. We are using a here string. Here strings allows large string data like an HTML page, to be placed into a string. Here strings are set apart using the @ symbol. Take a look at the $body below.

$body = @"
<html>
<header>Licenses</header>
<body>
<center>
<h1>Disabled Users</h1>
<h2>With Licenses</h2>
</center>
$ReturnString
</body>
</html>
"@

Params

Please note that some PowerShell ide does not like the tabbing inside a here-string. The next part is the parameters of the email system. We are sending a message. Additional documentation can be found here. We are going to use the following tags, subject, body, to recipient, and save to sent items. All of these items are setup as a Json file as the API uses Json as well.

  • Subject: What is the subject of the email
  • Body: body contains the content type and the content. Here is where we will be using our $body.
  • To Recipients: This is where the email addresses will go. We set up an email address and have it as an array.
  • Save to Sent Items: Finally, we determine if we want this item to stay in our sent items.
$params = @{
    message = @{
        subject = "Disabled Users with Licenses"
        body = @{
            contentType = "HTML"
            content = $body
        }
        toRecipients = @(
            @{
                emailAddress = @{
                    address = $Emailreceive
                }
            }
        )
    }
    saveToSentItems = "false"
}

Finally, we use the send-mgusermail command. This is where we use the send email. It will be the UPN of the target user we want to send email from. The body parameter will be the parameters we just built. Once you do this, you will see the email come in accordingly. That’s how you can send Emails with Graph API.

Find Disabled Users with Graph API and Powershell

Find Disabled Users with Graph API and Powershell

Microsoft licensing can cost a lot of money. It’s not logical to have a disabled account have licenses. Some licenses can cost up to $25 USD a month. So if you have 4 of these disabled accounts with licenses, that could easily be 100 per month. Let us Find Disabled Users with Graph API using PowerShell and find which ones have licenses.

Today’s post will be using the Microsoft.graph.users module. We can connect to graph API via the API, or we can use the Powershell module. In previous posts, I have shown how to connect to the API and pull information. This is still one of the best methods to use as the Graph API module has no way to search for things like shared mailboxes. I will cover that in a later post. So, let’s dive into the graph users module. You can read the documentation here.

The script

import-module Microsoft.Graph.Users
Connect-MgGraph -Scopes "User.Read.All"
$users = Get-MgUser -filter "accountenabled eq false"
foreach ($user in $users) {
    if ($null -ne (Get-MgUserLicenseDetail -UserId $user.Id)) {
        [pscustomobject][ordered]@{
            UPN = $user.UserPrincipalName
            Licenses = (Get-MgUserLicenseDetail -UserId $user.id).SkuPartNumber -join ", "
        }
    }
}
Disconnect-mggraph

The Breakdown

First of all, look at how little code there is compared to the previous post. The Connect-MGGraph removes so much back end work. When you run this command it will prompt you to grant it permissions. Once you disconnect, those permissions disappear. if you have a global admin account, if you don’t put in a scope, you gain access to everything. Which is super nice and scary. I prefer to have scope so I don’t break things.

If you don’t have the “Microsoft.Graph.Users” module, install it. You can install it by using the install-module commandlet.

Connect-MgGraph -Scopes "User.Read.All"

Like I said before, The connect-MGgraph command allows you to do scopes. This is very important. Back in the day we used msol. When we connected we had full control unless we limited our accounts which caused issues. In this case we are creating a temporary azure app. See the previous post about how to make an azure app. You will see how time saver this command can be. That azure app will have the scopes that you give it. If you don’t give it a scope, it has your rights. So, if you are a global admin, you can do damage on accident. It’s nice not to be in the scary ages anymore. So give it scope. In this case we are using User.Read.All as our scope. The User.Read.All permissions will help us Find Disabled Users.

$users = Get-MgUser -filter "accountenabled eq false"

The next part is where we grab all the disabled accounts. Using the Get-MgUser commandlet, we trigger the filter option. We want only accounts that are not enabled. thus the account enabled is equal to false. Very simple idea. If you run users[1] you can see the items you can search with. I do not suggest searching for anything to crazy.

The loop

Now we have all the disabled accounts we want to find the Licensed ones. We need to create a for each loop. Foreach loops are a staple for data controls. Without it… it’s just a pain. As we loop, we want to find the ones with a licenses. We need the user id from the account. So the best thing to do is do an if statement.

foreach ($user in $users) {
    if ($null -ne (Get-MgUserLicenseDetail -UserId $user.Id)) {
       #Do Something
    }
}

In this if statement we pull the licenses using the Get-MgUserLicenseDetail with the users id. If there is nothing that comes from this command it will return a null. So we test null against the command. It’s slightly faster than testing the command against null. Every user inside this if statement that is true will have a licensing. We want to display that information.

[pscustomobject][ordered]@{
        UPN = $user.UserPrincipalName
        Licenses = (Get-MgUserLicenseDetail -UserId $user.id).SkuPartNumber -join ", "
}

Here we create a PowerShell custom object. We want to display the User Principal Name, also known as, the sign name. We do this by using the $user from the foreach loop and just tag the user principal name. Next, we want to display all the licenses. The licenses come as an array. For example, my test account has 3 licenses. I want all that as a string. So, we use the Get-mguserlicensedetail command. We pull out the SKU part number. Then we do some array magic. The -join “, ” converts the array into a string. At the end of each line it adds a “,” and a space. Which makes it easier to read. The cool part about this is if it’s just one license, we it will not add the “, ” to the end. This makes it super readable.

One catch though, thanks to how Microsoft likes to hide things, the SKU is going to be coded. For example, it might say spe_f1. which means it’s an F1 license for Microsoft office. while of1 could mean the same thing but purchased from a different location. I use to try to keep a living list, however, these sku change daily and finding them will be hard. This is where Google is your friend.

Disconnect-MgGraph

Finally, we disconnect from graph API. We don’t want that app to stay there do we? Yeah, we disconnect like good admins we are. Once you are disconnected, you can review all the information this script provided. I am not a big fan of automating the removal of licenses through this method because many times other admins will licenses disabled accounts to keep email alive as a shared mailbox or other oddities. Right now, graph API poweshell module just doesn’t work with shared mailboxes. It is on the workbooks though.

Now go, Find Disabled Users With Graph API and Powershell, and Enjoy your day.

Microsoft Graph API PowerShell

Microsoft Graph API PowerShell

In the last blog, We talked about how to create a registered app with Graph API permissions. This app’s main purpose is to become the base for an employee directory through Powershell. If you haven’t read it yet, you can here. Today’s blog is about how to interact with the app with PowerShell. Here are the pieces of information you will need from the Application.

  1. The Tenant’s ID
  2. The Application ID
  3. The Secret Key

If you have those three pieces of information, we can build a script to grab all the users. The app has “User.Read.All” permissions. What this means is that the app can pull all the information inside the azure ad that is directly linked to the user’s Azure AD account. This does not include things like SharePoint, mail, etc, directory, teams, etc. You have to grant permission for those items. But items like name, usernames, images, and much more is accessible as read-only.

The first thing we want to do is put the required information into variables to be used over again and again.

$AppID = "XXXXXXXX-XXXX-xxxx-xxxx-xxxxxxxxxxxx"
$AppKey = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
$ClientID = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"

Next, we want to make a variable that will host the clientID inside the Oauth URL string. We use this string to authenticate later we want to grab the access token.

$Token = "https://login.microsoftonline.com/$($ClientID)/oauth2/v2.0/token"

The body of the access token requires a redirect url. You can set this as “http://localhost” if you want. We really don’t care unless the app has a redirected URL assigned to it. That’s for another day. So, the next step is to build the body. We do this with a basic hash table. Inside this table, we need client_id, client_secret, redirect_url, grant_type, and the scope.

$Body = @{
        client_id     = "$AppID"
        client_secret = "$AppKey"
        redirect_url  = "$redirect_url"
        grant_type    = "client_credentials"
        scope         = "https://graph.microsoft.com/.default"
}

Now we have the Token URL, and the body. We need to get the access token. We do this with a post method to the Token URL using the body information. Then we place that token in its own variable to be used in the header.

$request = Invoke-RestMethod -Uri $token -Body $Body -Method Post
$Access_Token = $request.access_token

Now we need to create the header. We are using the Authorization inside the header. We bear the access token inside the header.

$Header = @{
        Authorization = "Bearer $($Access_Token)"
}

Up to this point, we have been building the header for the next command. Now we need to switch gears and create the query URL for the graph. You can build out the string inside the graph explorer (Link) and read up on the documentation. The permissions give us access to the users’ information. You can read up on the query statement at this link.

In our example, we want to get a list of all users and these values.

  • First Name
  • Last Name
  • Display Name
  • Email Address
  • What they use to sign in with
  • Job Title
  • Account Enabled
  • Assigned Licenses.
$userInfoLink = 'https://graph.microsoft.com/v1.0/users?$select=givenname,surname,displayName,mail,userPrincipalName,jobtitle,accountenabled,assignedlicenses'

We are using the /users api to gather this information. Hint to the User.Read.All permissions we gave in the last blog post. Now, we grab the first piece of information using Invoke-RestMethod.

$PageInfo = Invoke-RestMethod -Headers $Header -Uri $UserInfoLink -method get 
$PageInfo.Value
$Userinfo = $PageInfo.Value

BAM! we have information. $PageInfo.Value will give you the first hundred records. Wait, only the first 100? Yep, Graph only presents the first 100 items. So, how do you handle that? You create a loop. how do we determine if we need a loop, we look to see if the value ‘@odata.nextlink’ exists. We do this with a Do While loop and the ‘@odata.nextlink’ information. The ‘@odata.nextlink’ is the next link request that will need to be executed. AKA the next page of the outcome. So each time the loop has a ‘@odata.nextlink’ the final loop will stop because it doesn’t have the link.

Do {
        $PageInfo = Invoke-RestMethod -Headers $Header -Uri $PageInfo.'@odata.nextlink' -Method Get
        $Userinfo += $PageInfo.Value 
} while (($PageInfo | Get-Member).name -contains '@odata.nextlink')

Notice we keep adding $PageInfo.Value to userinfo. This is building the userinfo array. This way we have the data we need. One of the requirements for this script is to have the Assigned user Information. So we need to add the sku part number of each license to the user. The problem is the assigned licenses gives back only the skuID. So what we can do is loop through the $UserInfo and add them accordingly. So we do this by starting a For Loop. Why a for loop? Because we will be adding a member property of the sku part numbers.

for ($I = 0; $I -lt $Userinfo.count; $I++) {
}

Inside this loop, we need to get the users’ licenses. We can do that with graphs as well. It’s still part of the user.read.all permissions as it still uses the /users api. We select the user by giving the UPN name. Then we ask for the license details with a /licenseDetails. I know super complex. Here is what the link will look like

for ($I = 0; $I -lt $Userinfo.count; $I++) {
        $LiceLink = "https://graph.microsoft.com/v1.0/users/$($UserInfo[-1].Userprincipalname)/licenseDetails"
}

Next we invoke the rest method again and using the link we generated pull in the information. I have never seen a user have more than 20 licenses. So, no need for a loop here.

for ($I = 0; $I -lt $Userinfo.count; $I++) {
        $LiceLink = "https://graph.microsoft.com/v1.0/users/$($UserInfo[-1].Userprincipalname)/licenseDetails"
        $UserLice = (Invoke-restmethod -Headers $Header -Uri $LiceLink -Method Get).value
}

Finally, we use the Add-Member feature to add a licensing information variable with the sku part number of each licenses inside that user’s account.

for ($I = 0; $I -lt $Userinfo.count; $I++) {
        $LiceLink = "https://graph.microsoft.com/v1.0/users/$($UserInfo[-1].Userprincipalname)/licenseDetails"
        $UserLice = (Invoke-restmethod -Headers $Header -Uri $LiceLink -Method Get).value
        $UserInfo[$i] | Add-Member -Name "LicenseInfo" -MemberType NoteProperty -Value $UserLice.skupartnumber
}

Each time the loop runs, it pulls that User’s UPN from the UserInfo array. Grabs the details of the license from graph and pulls only the sku part number. Then adds that part number to the license info inside the UserInfo array at that location. Let’s put it all together now.

The Script

Function Get-GraphEmployeeReport {
    [cmdletbinding()]
    param (
        [string]$org,
        [string]$AppID = (Read-Host -Prompt "AppId"),
        [string]$AppKey = (Read-Host -Prompt "AppKey"),
        [string]$ClientID = (Read-Host -Prompt "ClientID"),
        [string]$redirect_url = "https://localhost",
        [string]$OutfilePath = "C:\FMIT\Reports\MFA",
        [switch]$Output
    )
    $Token = "https://login.microsoftonline.com/$($ClientID)/oauth2/v2.0/token"
    $Body = @{
        client_id     = "$AppID"
        client_secret = "$AppKey"
        redirect_url  = "$redirect_url"
        grant_type    = "client_credentials"
        scope         = "https://graph.microsoft.com/.default"
    }
    $request = Invoke-RestMethod -Uri $token -Body $Body -Method Post
    $Access_Token = $request.access_token
    
    $Header = @{
        Authorization = "Bearer $($Access_Token)"
    }
    $userInfoLink = 'https://graph.microsoft.com/v1.0/users?$select=givenname,surname,displayName,mail,userPrincipalName,jobtitle,accountenabled,assignedLicenses'
    $PageInfo = Invoke-RestMethod -Headers $Header -Uri $UserInfoLink -method get #| where-object { ($_.assignedLicenses.count -gt 0) -and ($_.accountEnabled -eq $true) }
    $Userinfo = $PageInfo.Value
    Do {
        $PageInfo = Invoke-RestMethod -Headers $Header -Uri $PageInfo.'@odata.nextlink' -Method Get
        $Userinfo += $PageInfo.Value 
    } while (($PageInfo | Get-Member).name -contains '@odata.nextlink')
    for ($I = 0; $I -lt $Userinfo.count; $I++) {
        $LiceLink = "https://graph.microsoft.com/v1.0/users/$($UserInfo[-1].Userprincipalname)/licenseDetails"
        $UserLice = (Invoke-restmethod -Headers $Header -Uri $LiceLink -Method Get).value
        $UserInfo[$i] | Add-Member -Name "LicenseInfo" -MemberType NoteProperty -Value $UserLice.skupartnumber
    }
    $Userinfo
}

That’s all it takes to get the information from the azure ad. You can export this data into an XML or JSON and integrate it with any other system that you like. This does work with Powershell universal as well. You can create a table that has the next button or just gather all the information at once and present it. The more times it looks the longer the information will take to populate. Using the User.Read.All, you are also able to pull photos with graph API.

If you have any more questions, feel free to ask.