Skip to content

Instantly share code, notes, and snippets.

@PrateekKumarSingh
Last active September 30, 2022 01:48
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save PrateekKumarSingh/e2a3e1d920eddd00fc3e6370008fb95d to your computer and use it in GitHub Desktop.
Save PrateekKumarSingh/e2a3e1d920eddd00fc3e6370008fb95d to your computer and use it in GitHub Desktop.
<#
.Synopsis
Gets information of a port number
.DESCRIPTION
Function provides detailed information of port numbers, like - the service which use the port, Transport protocol and a small decsription.
.EXAMPLE
PS > Get-Port -Port 20,21,53
Port Service Protocol Description
---- ------- -------- -----------
20 ftp-data tcp File Transfer [Default Data]
20 ftp-data udp File Transfer [Default Data]
20 ftp-data sctp FTP
21 ftp tcp File Transfer Protocol [Control]
21 ftp udp File Transfer Protocol [Control]
21 ftp sctp FTP
53 domain tcp Domain Name Server
53 domain udp Domain Name Server
.EXAMPLE
PS > 135, 25, 23 | Get-Port
Port Service Protocol Description
---- ------- -------- -----------
135 epmap tcp DCE endpoint resolution
135 epmap udp DCE endpoint resolution
25 smtp tcp Simple Mail Transfer
25 smtp udp Simple Mail Transfer
23 telnet tcp Telnet
23 telnet udp Telnet
.EXAMPLE
PS > port 389
Port Service Protocol Description
---- ------- -------- -----------
389 ldap tcp Lightweight Directory Access Protocol
389 ldap udp Lightweight Directory Access P
#>
Function Get-Port
{
[CmdletBinding(HelpUri ='https://geekeefy.wordpress.com/2017/05/09/query-port-information-using-powershell/')]
[Alias('port')]
[OutputType([psobject])]
Param
(
[Parameter(
Mandatory=$true,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true,
Position=0,
HelpMessage="Please provide a port number")]
[ValidateRange(0,65536)][int[]]$Port
)
Begin
{
$TempFileName = "$env:TEMP\Ports.csv"
If(Test-Path $TempFileName){
$Data = Import-Csv $TempFileName
}
else{
$Data = Invoke-WebRequest 'https://goo.gl/G1i6RU' | `
ForEach-Object content | `
Tee-Object -FilePath $TempFileName -Verbose | ConvertFrom-Csv
}
}
Process
{
$Port | ForEach-Object {
$pv= $_
$Data.Where({$_.port -eq $pv})
}
}
End
{
Remove-Variable -Name Data
[gc]::Collect()
}
}
Copy link

ghost commented May 9, 2017

You can combine this with something like

(Get-NetTCPConnection -State Listen).LocalPort

to map open system ports to their related service names

@PrateekKumarSingh
Copy link
Author

Thanks for the tip, I didn't cross my mind. appreciate that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment