Validating IP Addresses in PowerShell

Spread the love

I had a client ask me to write a PowerShell script (for an Azure Automation runbook) to automate the creation of firewall rules for an Azure SQL Database. As part of this process, I was planning on having to validate the IP addresses (a valid IP address is of the format x.x.x.x where x is an integer between 0 and 255) by having to write some code to split the IP address string into individual octets and figuring out if each value was a valid number. However, in doing research (searching Stack Overflow), I discovered PowerShell has a built-in IP address data type, which made my life way easier.

Since PowerShell has IPAddress as a data type, that means we can attempt to cast a string value as a data type.

If I type an invalid IP address I get the following result:

You’ll note I don’t get an error, I simply don’t get a result. For me to do something useful with this I do have to write a little more code to handle this IP address in my script.

try {

$s=$StartIP -as [ipaddress] -as [Bool] $e=$EndIP -as [ipaddress] -as [Bool]
if ($s -eq $false -or -$e -eq $false){write-error "Invalid IP Address"}

After casting my parameters as an IPAddress, I can then cast them as a boolean. A boolean value is a yes/no value that in PowerShell will return a $True/$False value. If the IP addresss submitted is a valid one, the result will be true. In my IF loop, I’m saying if either my start or end IP addresses are invalid to write an error stating such.

1 thought on “Validating IP Addresses in PowerShell

  1. Pingback: Validating IP Addresses using Powershell – Curated SQL

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.