Get-PostCodeAddress.ps1


<#PSScriptInfo
 
.VERSION 1.0
 
.GUID 31863f80-0475-47fa-9153-66e8119ffa92
 
.AUTHOR liambinnsconroy@gmail.com
 
.COMPANYNAME
 
.COPYRIGHT (C) Liam Binns-Conroy. All rights reserved.
 
.TAGS
 
.LICENSEURI
 
.PROJECTURI
 
.ICONURI
 
.EXTERNALMODULEDEPENDENCIES
 
.REQUIREDSCRIPTS
 
.EXTERNALSCRIPTDEPENDENCIES
 
.RELEASENOTES
 
 
#>


<#
 
.SYNOPSIS
    Gets an address from each postal code in the input file.
.DESCRIPTION
    Given a file containing a list of postal codes, gets and outputs an address for each code. Uses the google maps api.
.PARAMETER Path
    The path to the file containing the list of post codes. Mandatory.
.PARAMETER CountryCode
    The country code to help refine the search results e.g. NZ.
    Not mandatory but almost essential for countries outside the US.
.EXAMPLE
    Get-PostCodeAddress `
        -Path 'C:\postcodes.txt' `
        -CountryCode 'NZ' `
        -Verbose
 
    postcodes.txt:
    3210
    1061
 
    Output is:
    2 Cherie Cl, Rototuna, Hamilton 3210, New Zealand
    269A Mount Smart Rd, Onehunga, Auckland 1061, New Zealand
 
#>
 
param
(
    [Parameter(Mandatory)]
    [String] $Path,

    [String] $CountryCode
)

# Get the postcodes from the txt file
$postCodes = Get-Content -Path $Path

foreach ($postcode in $postCodes) {
    # Get the coordinates of the post code
    $postCodeCoords = Invoke-RestMethod -Method GET -Uri "http://maps.googleapis.com/maps/api/geocode/json?address=$postcode $CountryCode"

    $postCodeLat = $postCodeCoords.results.geometry.location.lat
    $postCodeLong = $postCodeCoords.results.geometry.location.lng

    # Get an address in that postcode
    $address = Invoke-RestMethod -Method GET -Uri "http://maps.googleapis.com/maps/api/geocode/json?address=$postCodeLat,$postCodeLong&location_type=ROOFTOP&result_type=street_address"

    # Return the address
    $address.results.formatted_address[0]
}