Posted On January 30, 2023

PowerShell: Get Connected Port by Process Name

kimconnect 0 comments
blog.KimConnect.com >> Codes , Windows >> PowerShell: Get Connected Port by Process Name
# getProcessConnectionPort.ps1

$computerlist=@'
SQL1
SQL2
'@

$computernames=@($computerList -split "`n")|%{$_.Trim()}
$processname='sqlservr'
$state='Established'

$results=@()
foreach ($computername in $computernames){
    $result=invoke-command -computername $computername{
        param($processName,$state='Established')
        try{
            $processid=(get-process $processName).Id            
            $ports=Get-NetTcpConnection -OwningProcess $processid -State $state|Group-Object -Property LocalPort
            write-host "$env:computername`: $processName PID is found as $processid running on port(s) $($ports.Name)"
            return $ports
        }catch{
            write-warning $_
            return $false
        }        
    } -Args $processName,$state
    $results+=$result
}
$results

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Post

PowerShell: Add Root Domain to Trusted Sites

Windows Servers often have 'hard admin' modes, where accesses to external websites are painstakingly restricted.…

PowerShell: How To Make A System App Do Nothing

# How-To-Make-Existing-System-App-Do-Nothing.ps1# Provide variables$hive="REGISTRY::HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\WORDPAD.EXE"$key="(default)"$value="C:\Windows\dummy.exe"$defaultValue="C:\Program Files\Windows NT\Accessories\WORDPAD.EXE"# Dummy-File-Creator.ps1$dummyFile="C:\Windows\dummy.exe"$output = new-object byte[] 1; (new-object Random).NextBytes($output);[IO.File]::WriteAllBytes($dummyFile, $output);if…

PowerShell: Add System Backup Privileges

function addSystemPrivilege{ param( [String[]]$privileges=@("SeBackupPrivilege","SeRestorePrivilege") ) function includeSystemPrivileges{ $win32api = @' using System; using System.Runtime.InteropServices; namespace…