Dave Herrell - Blog - IT Toolbox - PowerShell Banner

PowerShell Basics: Expiring Domain Slack Alerts

Managing a large number of domain names can be a tedious task, especially when it comes to tracking expiration dates. This PowerShell script automates this process, making it easy to stay on top of your domain renewals.

How it works:

  1. Create a domain list: Prepare a simple text file containing all the domain names you want to monitor.
  2. Set up Slack webhook: Configure an incoming webhook URL in your Slack workspace to receive alerts.
  3. Run the script: Execute the script, providing the Slack webhook URL and the path to your domain list.

The script will:

  • Scan the domain list for expirations within the next 30 days.
  • Send a timely alert to your designated Slack channel for each impending expiration.

Need help with the Slack webhook setup?  I’ve included a brief guide below to get you started.

Create Slack Webhook

Log into your Slack workspace as an administrator.  Go to the admin section of Slack.   On the left menu list, scroll down to Configure Apps. 

Choose the Custom Integrations. You can also utilize Slack apps for this.  But for this round, we’ll use Slacks Incoming Webhooks.   Choose Incoming Webhooks, then click the Add to Slack button.

Choose the Channel you want the alerts to go into.  In this example I will use a private channel I created named “domain-expiration-alerts”.   Once you chose the channel, click “Add Incoming Webhooks integration”.    This will send an alert to the channel you just chose. 

Next we’ll configure the basics of the alert such as its Custom name, Label Icon, Etc. Once complete, click Save Settings.  You will also notice the app name in your channel alert has updated. 

Dont be a noob.  The webook in this screenshot has already been removed.

Last thing you need to do is copy the Webhook URL.  You will need this for the PowerShell script. 

Looking to do this with Python instead?  Check this page out

PowerShell Script

Now that you have your Slack Webhook URL, it’s time to setup your alert script.   Below is the script you can copy.  Make sure you update the .txt file path and Webhook URL with your own information. 

 

				
					# Define the path to your input file containing domain names (one per line)
$inputFilePath = "/Users/daveherrell/Desktop/domains.txt"

# Define your Slack webhook URL (replace with your actual Slack webhook URL)
$slackWebhookUrl = "https://hooks.slack.com/services/LOTSOFNUMERSANDLETTERS"

# Define the number of days threshold for notification
$expirationThreshold = 30

# Check if the input file exists
if (-not (Test-Path $inputFilePath)) {
    Write-Output "Input file not found at $inputFilePath"
    exit
}

# Initialize an array to collect the domains nearing expiration
$expiringDomains = @()

# Loop through each domain in the input file
Get-Content $inputFilePath | ForEach-Object {
    $domain = $_.Trim()
    
    if ($domain) {
        try {
            # Perform WHOIS lookup using the `whois` command
            $whoisInfo = whois $domain

            # Determine the TLD of the domain (e.g., .com, .org, etc.)
            $tld = ($domain -split "\.")[-1]

            # Parse expiration date and registrar based on TLD
            if ($tld -eq "org") {
                # Parsing for .org domains
                $expirationDateString = ($whoisInfo | Select-String -Pattern "Registry Expiry Date:\s*(.*)").Matches[0].Groups[1].Value.Trim()
                $registrar = ($whoisInfo | Select-String -Pattern "Registrar:\s*(.*)").Matches[0].Groups[1].Value.Trim()
            } else {
                # Default parsing for other domains (like .com)
                $expirationDateString = ($whoisInfo | Select-String -Pattern "Expiration Date:\s*(.*)").Matches[0].Groups[1].Value.Trim()
                $registrar = ($whoisInfo | Select-String -Pattern "Registrar:\s*(.*)").Matches[0].Groups[1].Value.Trim()
            }

            # Parse the expiration date
            $expirationDate = [datetime]::Parse($expirationDateString)

            # Calculate days until expiration
            $daysUntilExpiration = ($expirationDate - (Get-Date)).Days

            # Check if the domain is expiring within the threshold
            if ($daysUntilExpiration -le $expirationThreshold) {
                # Add the expiring domain information to the array
                $expiringDomains += [PSCustomObject]@{
                    Domain = $domain
                    ExpirationDate = $expirationDate
                    DaysUntilExpiration = $daysUntilExpiration
                    Registrar = $registrar
                }
            }

            Write-Output "Processed $domain"
        } catch {
            Write-Output "Failed to process {$domain}: $_"
        }
    }
}

# Format the message to send to Slack if there are expiring domains
if ($expiringDomains.Count -gt 0) {
    $slackMessage = "Domains Expiring Soon (Within $expirationThreshold Days):`n"
    foreach ($domainInfo in $expiringDomains) {
        $slackMessage += "`n*Domain:* $($domainInfo.Domain)`n*Expiration Date:* $($domainInfo.ExpirationDate.ToString("yyyy-MM-dd"))`n*Days Until Expiration:* $($domainInfo.DaysUntilExpiration)`n*Registrar:* $($domainInfo.Registrar)`n"
    }

    # Send the message to Slack
    try {
        $payload = @{
            text = $slackMessage
        }
        $payloadJson = $payload | ConvertTo-Json -Compress

        Invoke-RestMethod -Uri $slackWebhookUrl -Method Post -ContentType "application/json" -Body $payloadJson

        Write-Output "Message sent to Slack successfully!"
    } catch {
        Write-Output "Failed to send message to Slack: $_"
    }
} else {
    Write-Output "No domains are expiring within $expirationThreshold days."
}

Write-Output "Done!"
				
			

A couple items to note:

  • You can change the date range on line 8 with whatever you wish.  Just make sure it’s in days.  For instance you can set it for 90 days instead of 30 days.
  • WHOIS results may vary, so adjust parsing (Select-String patterns) as needed.
  • Within your TXT file, you can list up to 10 thousand domains before this breaks.  However, make sure the file only contains one domain per line!
  • You can easily set this script to run via Scheduled task on Windows server.  
  • Even if the domain in the txt file is no longer available, the script will still run. 

The Results

Finally you should be able to run your PowerShell Script and receive your alerts.  You should get a similar Slack alert:

 

Domains I knew were expiring were used in this example.

And there you have it.  Simple Alerts to your Slack Channel. 

Hope you find this helpful!