Using Cached Port File

by Jun 22, 2017

In the previous tip we explained how you can download port assignments via PowerShell from IANA. This process requires Internet access and can take a while. So here is code that looks for a cached CSV file. If it is present, port data is loaded from file offline, else the data is retrieved online, and a cache file is written. Note especially how Tee-Object is used to create the cache file:

$url = 'https://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.csv'
$CSVFile = "$env:temp\ports.csv"
$exists = Test-Path -Path $CSVFile

if (!$exists)
{
  Write-Warning "Retrieving data online..."

  $portinfo = Invoke-WebRequest -Uri $Url -UseBasicParsing | `
    Select-Object -ExpandProperty Content | `
    Tee-Object -FilePath $CSVFile | ConvertFrom-Csv
}
else
{
  Write-Warning "Loading cached file..."
  $portinfo = Import-Csv -Path $CSVFile
}

$portinfo | Out-GridView

Twitter This Tip! ReTweet this Tip!