Use Rebrandly API with PowerShell

I am using Rebrandly to shorten my Links for Social Media Posts. I also automated these Steps with my Planning Excel sheet, that Link will be generated automatically. Unfortunately, there was a Bug, and each time I opened the Excel Sheet, new Links have been generated.

So there has been a lot of Links in a short time, now I wanted to do a cleanup, but not manually 🙂

So we need a PowerShell Script, which will delete all Links with Zero Clicks and older than a specific Range.

REBRANDLY API Documentation

Of course, before we start, we read the Documentation 🙂

So I figured out how the API works and what I need to get started here: API for custom short URLs – Code snippet (rebrandly.com)

Most importantly, get your API KEY to making sure you can authenticate with the API.

Script

Here you find the complete Script with inline Comments

#Rebrandly API Key https://developers.rebrandly.com/docs/api-key-authentication
$APIKEY = "yourKEy"

#Configure Daterange to delete older Links
$TimeSpanMonth = 2

#Rebrandly API Header with API Key
$headers = @{
  "apikey" = "$APIKEY"
}

#Get all Links with Paging
$URL = "https://api.rebrandly.com/v1/links"
$AllLinks = @()
do {
  
  if ($AllLinks) {
    $Latest = $AllLinks | Select-object -last 1
    $URL = "https://api.rebrandly.com/v1/links?last=$($Latest.id)"
  }

  $Repsonse = Invoke-RestMethod -Method GET -Uri $URL -Headers $headers
  $AllLinks += $Repsonse

  
} while ($Repsonse.count -gt 0)

#Amount of Links
$AllLinks.count

#Get Links with Zero Clicks
$ZeroClickLinks = $AllLinks | Where-Object -Property clicks -Value 0 -eq
$ZeroClickLinks.count


#Get Zero links older than Timepsan
$Limit = Get-Date -Format O (Get-Date).AddMonths(-$TimeSpanMonth)
$OlderLinks = $ZeroClickLinks | Where-Object -Property createdAt -Value $Limit -lt

$OlderLinks.count



#Go through each Link and Delete
foreach ($O in $OlderLinks) {

  $URLdelete = "https://api.rebrandly.com/v1/links/$($o.id)"
  Invoke-RestMethod -Method DELETE -Uri $URLdelete -Headers $headers

}

Github Repo

Here is my REBRANDYL GitHub Repo: Seidlm/REBRANDLY-PowerShell: Some examples on how to use Rebrandly API with PowerShell (github.com)

Michael Seidl aka Techguy
au2mator everything

Leave a Comment

Your email address will not be published.

*

%d bloggers like this: