Retrieve the Port of an SQL Instance in PowerShell

Retrieve the Port of an SQL Instance in PowerShell
The default port for an MS SQL server is 1433, but you will often find that for security reasons, the port has been changed.
Here is a small PowerShell script to return the instances and the ports used by an MS SQL server.
$server = Read-Host -Prompt 'Input your servername'
$namespace = gwmi -computername $server -Namespace "root\microsoft\sqlserver" -Class "__Namespace" -Filter "name like 'ComputerManagement%'" | sort desc | select -ExpandProperty name -First 1
Get-WmiObject -computername $server -Namespace "root\microsoft\SqlServer\$namespace" -Class ServerNetworkProtocolProperty | select instancename,propertystrval,PropertyName,IPAddressName,ProtocolName | where{$_.IPAddressName -eq 'IPAll' -and $_.propertystrval -ne ''} | ft -autosize
When you execute this script, it will prompt you to input the server for which you want to find the instances and ports. You will then get a result like this:
Enjoy! 😉

Authors
SysOps Engineer | IT Teacher
Versatile IT Engineer with a dual specialization in System Engineering and Management, AlexIn Tech teaches IT to CFC apprentice IT specialists at ETML, the Technical School of Lausanne 🇨🇭. Passionate about IT, innovation, and knowledge sharing, he shares his discoveries and learnings here to inspire new generations.