PSCONF EU: Use PowerShell to read Inbox and draw a contest Winner

I was at the PSCONF EU 2022 as a Premium Sponsor with au2mator. We had a Contest, where the Attendees need to sign up and an email was sent.

The Challenge was, to select 3 Random Winners from that list. As we are at PowerShell Conference, we wanted to find a PowerShell way to solve this.

So we created an Azure App Registration and read the Inbox, did some formatting, and get 3 Random Names for the Comic, and 3 random Names for the BaseCaps.

References:

If you are not familiar with Azure App Regs, and how all this work together, see my Blogs Post for Details:

To learn more from Microsoft GRAPH API, see my Blog Series:
Part 1 – Authentication and Azure App – Use Microsoft Graph API with PowerShell – Part 1 » TechGuy
Part 2 – Oauth2.0 – Use Microsoft Graph API with PowerShell – Part 2 » TechGuy
Part 3 – First Powershell Script to get a Teams Lis and Walkthrough – Use Microsoft Graph API with PowerShell – Part 3 » TechGuy
Part 4 – this one – Use Microsoft Graph API with PowerShell – Part 4 » TechGuy

The Script


$clientID = "your-ClientID"
$Clientsecret = "your-Secret"
$tenantID = "your-TenantID"

$BaseURL="https://graph.microsoft.com/v1.0"

$UserUPN="michael.seidl@au2mator.com"
$MailArray=@()




#Connect to GRAPH API
$tokenBody = @{
    Grant_Type    = "client_credentials"
    Scope         = "https://graph.microsoft.com/.default"
    Client_Id     = $clientId
    Client_Secret = $clientSecret
}
$tokenResponse = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$tenantID/oauth2/v2.0/token" -Method POST -Body $tokenBody
$headers = @{
    "Authorization" = "Bearer $($tokenResponse.access_token)"
    "Content-type"  = "application/json"
}

$URLReadFolder="$BaseURL/users/$UserUPN/mailFolders"
$Inboxfolder=(Invoke-RestMethod -Method GET -Uri $URLReadFolder -Headers $headers).value | Where-Object -Property displayname -Value Inbox -eq

$URLReadMail="$BaseURL/users/$UserUPN/mailFolders/$($Inboxfolder.id)/messages?`$filter=startswith(Subject,'au2mator - Self Service Portal')"
$Mails=Invoke-RestMethod -Method GET -Uri $URLReadMail -Headers $headers

foreach ($M in $Mails.value)
{
    $Mailarray+=$M.body.content.substring(0,$M.body.content.IndexOf(")")+1).replace("From: ","")
}
""
""
""
"The Comic Winners are:"
""
$Comicwinners=$MailArray | Get-Random -Count 3
$Comicwinners
""
""
""


$MailArray = $MailArray |Where-Object { $Comicwinners -notcontains $_ }
#$MailArray.count
$BaseCapWinners=$MailArray | Get-Random -Count 3
""
""
""
"The BaseCap Winners are:"
""
$BaseCapWinners
""
""
""

GitHub Repo

Here you can find the GitHub Repo: Seidlm/PowerShell-Tools (github.com) with the Script

Michael Seidl aka Techguy
au2mate everything

Leave a Comment

Your email address will not be published.

*

%d bloggers like this: