PS: Check TCP Port in use and running process

If you have information, script, utility, or idea that can be useful for HostMonitor community, you welcome to share information in this forum.
Post Reply
sysadmber
Posts: 50
Joined: Tue Dec 08, 2015 1:26 am

PS: Check TCP Port in use and running process

Post by sysadmber »

Hostmon provides TCP Test by sending data to the port and checks it's answer. I needed a check whether the TCP port is open and if so by which process.

This scripts runs only locally, in my case via rma.

Here is the code:

Code: Select all

param(
[string]$param_port,
[string]$param_proc,
[string]$param_proc_desc = "'Please provide Program Description as third parameter'"
)

If (!$param_port){
    Return "ScriptRes:Bad:Program Abort - Please provide Port number as first parameter"
}
If (!$param_proc){
    Return "ScriptRes:Bad:Program Abort - Please provide process name as second parameter"
}
$process = get-process $param_proc
If (!$process.id){
    Return "ScriptRes:Bad: " + $param_proc_desc + " is not started"
}
$netcon = Get-NetTCPConnection -LocalPort $param_port

If ($netcon.State -eq "listen"){
    if ($netcon.OwningProcess -ne $process.id){
        $proc_alt = get-process -id $netcon.OwningProcess
        Return "ScriptRes:Bad:TCP Port " + $param_port + " is not in use by " + $param_proc_desc + " but " + $proc_alt.Name + " (PID: " + $proc_alt.Id + ")"
        }
    else{
        Return "ScriptRes:Ok:TCP Port " + $param_port + " is used by " + $param_proc_desc
    }
}
else{
        Return "ScriptRes:Bad:TCP Port " + $param_port + " is not in use"
}
Post Reply