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 Consultant | IT Teacher
Alexis is a SysOps Engineer and IT teacher at ETML in Lausanne. Rooted in systems and infrastructure, he combines automation and custom development with a growing interest in AI to solve practical problems. He offers IT consulting, custom solutions, and hosting.