Validate UK Postcodes with PowerShell
In this article I’ll explain how to use the Test-Postcode
cmdlet from the PowerShell Posh-Postcodes.io module to validate a CSV file of UK Postcodes.
Posh-Postcodes.io is a PowerShell module that leverages the Postcodes.io API used for working with UK postcode data, full details
can be found on the post covering the launch
Scenario
We have a .csv
comma-delimited text file containing various columns, one of which is a Postcode. We want to check that each of these postcodes are valid and exist and
flag up any incorrect entries.
An example CSV file used here can be downloaded from www.isjw.uk/resources/example-postcode-data.csv. Here’s an excerpt:
1"Club", "StadiumName", "Address1", "Address2", "City", "Postcode"
2"Manchester City", "Etihad Stadium", "Etihad Campus", "", "Manchester", "M11 3FF"
3"Liverpool", "Anfield Stadium", "Anfield Road", "Anfield", "Liverpool", "L4 0TH"
4"Brighton and Hove Albion", "Amex Stadium", "Village Way", "Brighton and Hove", "Brighton", "BN1 9BL"
5...
Solution
Start by installing the Posh-Postcodes.io module from the PowerShell Gallery:
1Install-Module Posh-Postcodes.io
The regular Invoke-WebRequest
and ConvertFrom-Csv
cmdlets can be used to download the example data and translate the comma-delimited text into a PowerShell object.
1$URL="https://isjw.uk/resources/example-postcode-data.csv"
2$PostcodeData=(Invoke-WebRequest -Uri $URL).Content | ConvertFrom-Csv
The imported data will look something like this, note that the field to be tested is (conveniently) titled Postcode
:
1PS C:\> $PostcodeData
2
3Club : Manchester City
4StadiumName : Etihad Stadium
5Address1 : Etihad Campus
6Address2 :
7City : Manchester
8Postcode : M11 3FF
9
10Club : Liverpool
11StadiumName : Anfield Stadium
12Address1 : Anfield Road
13Address2 : Anfield
14City : Liverpool
15Postcode : L4 0TH
16
17Club : Brighton and Hove Albion
18StadiumName : Amex Stadium
19...
Test-Postcode
from the Posh-Postcodes.io module is a method used to validate a postcode. We need to check each field containing a postcode in the data imported from the CSV file and return any cases where Test-Postcode
returns false.
That can be done with the following test:
1$PostcodeData | Where-Object {!(Test-Postcode -Postcode $_.Postcode)}
This should return just two entries from the example datafile where the postcodes are invalid.
1Club : Melchester Rovers
2StadiumName : Mel Park
3Address1 :
4Address2 :
5City : Chester
6Postcode : CH3 9ZZ
7
8Club : AFC Richmond
9StadiumName : Nelson Road Stadium
10Address1 : Nelson Road
11Address2 :
12City : Richmond
13Postcode : TW9 6YA