Skip to content

Instantly share code, notes, and snippets.

@arebee
Created August 29, 2019 23:37
Show Gist options
  • Save arebee/6d0cd0bd39493911324193e44e005437 to your computer and use it in GitHub Desktop.
Save arebee/6d0cd0bd39493911324193e44e005437 to your computer and use it in GitHub Desktop.
Get a Gravatar Image from an email address using PowerShell
<#
.SYNOPSIS
Retrieve an icon from Gravatar
.DESCRIPTION
Retrieve an icon from Gravatar for the provided email address.
.EXAMPLE
PS C:\> Get-Gravatar -EmailAddress 'sally@example.com'
Requests an image from Gravatar for the email address 'sally@example.com'
If available, it will write a 300 pixel square image in the working dirctory
with the name sally@example.com.jpg
.EXAMPLE
PS C:\> Get-Gravatar -EmailAddress 'sally@example.com' -Size 500 -Name 'Sally Sample'
Requests an image from Gravatar for the email address 'sally@example.com'
If available, it will write a 500 pixel square image in the working dirctory
with the name 'Sally Sample.jpg'
.PARAMETER EmailAddress
Required. An email address. Must be provided. Email address format not validated.
.PARAMETER Size
Optional. An integer between 1 and 2048 defining the size of the image returned from Gravatar.
Default value is 300 pixels. Images returned from Gravatar are square
.PARAMETER Name
Optional. Name used for the output filename. Defaults to the email address.
.NOTES
If there isn't an image in Gravatar, nothing is output.
#>
function Get-Gravatar {
param (
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]$EmailAddress,
[Parameter(Mandatory=$false)]
[ValidateRange(1,2048)]
[int]$Size = 300,
[Parameter(Mandatory=$false)]
[string]$Name = $EmailAddress
)
$emailAsBytes = [System.Text.Encoding]::UTF8.GetBytes($EmailAddress.Trim().ToLowerInvariant())
$stringBuilder = [System.Text.StringBuilder]::new()
$emailMd5Bytes = [System.Security.Cryptography.MD5]::Create()
$emailHashBytes = $emailMd5Bytes.ComputeHash($emailAsBytes)
for ($i = 0; $i -lt $emailHashBytes.Length; $i++) {
$stringBuilder.Append( $emailHashBytes[$i].ToString('x2') ) | Out-Null
}
try {
Invoke-WebRequest -Uri "https://www.gravatar.com/avatar/$($stringBuilder.ToString())?s=$Size&d=404" -OutFile $(Join-Path $pwd "$Name`.jpg")
} catch {
Write-Verbose "Error Occured $_"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment