Skip to content

Instantly share code, notes, and snippets.

@Techlogist
Last active February 7, 2021 14:10
Show Gist options
  • Save Techlogist/5197b6cbd6f62cbbc86d4a74f7dddf9e to your computer and use it in GitHub Desktop.
Save Techlogist/5197b6cbd6f62cbbc86d4a74f7dddf9e to your computer and use it in GitHub Desktop.
Elementary Powershell loop with conditions
$NARemotePort="0"
$NARemoteAddress="::","127.0.0.1"
$Array=""
ForEach ($OutIPPort in (Get-NetTCPConnection | Sort-Object -Property RemotePort)){...}
if ($OutIPPort.RemotePort -in $NARemotePort -or $OutIPPort.RemoteAddress -in $NARemoteAddress) {}
else{
$IPName=Get-Process -id $OutIPPort.OwningProcess | Select-Object Name;
$REMP=Resolve-DnsName $OutIPPort.RemoteAddress -ErrorAction SilentlyContinue | Select-Object NameHost
if($REMP.NameHost -eq $null) {$NameHost= "No record"} else {$NameHost=$REMP.NameHost}
$Detail1= $IPName.Name
$Detail2=$OutIPPort.OwningProcess
$Detail3=$OutIPPort.RemoteAddress
$Detail4=$NameHost
$Detail5=$OutIPPort.RemotePort
Write-Output "$Detail1 $Detail2 $Detail3 $Detail4 $Detail5"
# License: GNU General Public License v2.0
# Author: Miguel
# Website: www.techlogist.net
# Post: https://techlogist.net/powershell/elementary-powershell-loop-with-conditions/
# Description: Elementary Powershell loop with conditions
# OS/Language: Windows/EN-US
#Example of powershell loop with error fix
#Set the ports which will not be resolved
$NARemotePort="0"
$NARemoteAddress="::","127.0.0.1"
#Optain the properties
ForEach ($OutIPPort in (Get-NetTCPConnection | Sort-Object -Property RemotePort)){
if ($OutIPPort.RemotePort -in $NARemotePort -or $OutIPPort.RemoteAddress -in $NARemoteAddress) { }
else{
$IPName=Get-Process -id $OutIPPort.OwningProcess | Select-Object Name;
$REMP=Resolve-DnsName $OutIPPort.RemoteAddress -ErrorAction SilentlyContinue | Select-Object NameHost
if($REMP.NameHost -eq $null) {$NameHost= "No record"} else {$NameHost=$REMP.NameHost}
#Define the output variables
$Detail1=$IPName.Name
$Detail2=$OutIPPort.OwningProcess
$Detail3=$OutIPPort.RemoteAddress
$Detail4=$NameHost
$Detail5=$OutIPPort.RemotePort
#Output the result
Write-Output "$Detail1 $Detail2 $Detail3 $Detail4 $Detail5"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment