Get-PostCodeAddress.ps1


<#PSScriptInfo
 
.VERSION 1.01
 
.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. Either this or PostCode must be specified.
.PARAMETER PostCode
    A comma separated series of post codes, e.g. "3210","3216". Either this or Path must be specified.
.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
 
 
    Get-PostCodeAddress `
        -PostCode "3210","1061" `
        -CountryCode 'NZ' `
        -Verbose
 
    Output is:
    2 Cherie Cl, Rototuna, Hamilton 3210, New Zealand
    269A Mount Smart Rd, Onehunga, Auckland 1061, New Zealand
 
#>
 
param
(    
    [String] $Path,

    [String[]] $PostCode,

    [String] $CountryCode
)

# Get the postcodes from the txt file if it exists
if (!([String]::IsNullOrEmpty($Path))) {
    $postCodes = Get-Content -Path $Path
}
# Or if the user has specified an array
elseif(!([String]::IsNullOrEmpty($PostCode))) {
    $postCodes = $PostCode
}

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]
}