In this article tutorial, I will show you how to use a function from a PowerShell script.
Create a script named: Get-NetworkConnectionProcess.ps1.
Add this source code to your script:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | function Get-NetworkConnectionProcess { [CmdletBinding()] param ( [ValidateSet( 'Closed', 'CloseWait', 'Closing', 'DeleteTCB', 'Established', 'FinWait1', 'FinWait2', 'LastAck', 'Listen', 'SynReceived', 'SynSent', 'TimeWait')] [string]$State = 'Established' ) process { $TCPConnections = Get-NetTCPConnection -State $State | Select-Object -Property LocalPort, OwningProcess $Filter = "ProcessId=" + ($($TCPConnections.OwningProcess) -join " or ProcessId=") Write-Verbose "ProcessIds are $Filter" $TCPProcessesArguments = @{ ClassName = 'Win32_Process' Filter = $Filter Property = 'ProcessId', 'Name', 'CommandLine' } $TCPProcesses = Get-CimInstance @TCPProcessesArguments | Select-Object -Property ProcessId, Name, CommandLine foreach ($TCPConnection in $TCPConnections) { Write-Verbose "Processing $($TCPConnection.LocalPort)" $TCPProcess = $TCPProcesses | Where-Object -Property ProcessId -EQ -Value $TCPConnection.OwningProcess [PSCustomObject]@{ Port = $TCPConnection.LocalPort ProcessName = $TCPProcess.Name ProcessCmd = $TCPProcess.CommandLine } } } } |
Use the dot sourcing operator (.) to load the function into your PowerShell session, like this:
1 | . .\Get-NetworkConnectionProcess.ps1 |
The command will load the function and once is loaded, you can call it by name and pass any desired parameters, like this:
1 | Get-NetworkConnectionProcess -State 'Established' |