Get local port numbers in windows 7 [duplicate] - windows

This question already has answers here:
Get foreign address name using NETSTAT for established active TCP connections
(3 answers)
Closed 6 years ago.
I am trying to get all local ports that are in listening state. Using
netstat -a -n
I get the following output:
Proto Local Address Foreign Address State
TCP 0.0.0.0:8080 0.0.0.0:0 LISTENING //for example, demo data is given
But I only wan't to get the port numbers.
1111 //for ex, this is in listening state.
In Windows 10, I can use
Get-NetTCPConnection -State Listen | group localport -NoElement
Which works but this command isn't available on Windows 7

Not sure whether there is a Windows 7 cmdlet available but you could parse the netstat result:
$objects = netstat -a -n |
select -Skip 4 |
ForEach-Object {
$line = $_ -split ' ' | Where-Object {$_ -ne ''}
if ($line.Count -eq 4)
{
New-Object -TypeName psobject -Property #{
'Protocol'=$line[0]
'LocalAddress'=$line[1]
'ForeignAddress'=$line[2]
'State'=$line[3]}
}
}
Then you can retrieve the ports using something like this:
$objects | Where State -eq LISTENING | Select LocalAddress | Foreach {
$_ -replace '.*:(\d+).*', '$1'
}

Related

Get list all IP addresses connected to your server using Powershell / CMD

EDITED
my goal :
get "total" list of IP's connected to port 80 in windows server.
TOTAL IP's
5 1.1.1.1
12 2.2.2.2
1 3.3.3.3
in centos, i found this
netstat -tn 2>/dev/null | grep :80 | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -nr | head
but if windows server, is there any way do that using powershell or cmd?
*i get one example but its not reaching my goal :
netstat -n | find "80"
credit for example : https://mkyong.com/linux/list-all-ip-addresses-connected-to-your-server/
Get-NetTCPConnection is the PowerShell equivalent and creates a robust object you can filter to your needs.
In your example, you're getting all connections to port 80 on your device, here's what that looks like in PowerShell:
Get-NetTCPConnection |where RemotePort -eq 80
LocalAddress LocalPort RemoteAddress RemotePort State AppliedSetting OwningProcess
------------ --------- ------------- ---------- ----- -------------- -------------
192.168.0.27 51135 50.63.202.49 80 CloseWait Internet 12508
192.168.0.27 51134 50.63.202.49 80 CloseWait Internet 12508
192.168.0.27 51133 50.63.202.49 80 CloseWait Internet 12508
192.168.0.27 51132 50.63.202.49 80 CloseWait Internet 12508
If you wanted to gather just the remote IP addresses, for instance:
Get-NetTCPConnection |where RemotePort -eq 80 |select RemoteAddress
RemoteAddress
-------------
50.63.202.49
50.63.202.49
50.63.202.49
50.63.202.49
50.63.202.49
50.63.202.49
If you need to group them to see how many sessions per IP, you can pipe into the Group-Object cmdlet like so:
Get-NetTCPConnection |where RemotePort -eq 80 |select RemoteAddress |
group-object -Property RemoteAddress |select Name,Count
Name Count
---- -----
72.21.91.29 1
23.35.182.63 6
One quick and dirty way to find TCP sessions connected to port 80 is
for /f "tokens=3" %a in ('netstat -n ^| find ":80 "') do #echo %a > filename.txt
You would obtain output similar to the following:
10.1.1.3:52025
10.1.1.3:53014
10.1.1.3:53039
10.1.1.3:53044
10.1.1.3:53066

find process that is blocking a port on windows

I am trying to connect remote mssql server, but something on my machine is blocking the required 1433 port.
How to find what process/program is blocking outgoing traffic on that port.
All firewall/antiviruses are disabled.
From the command line:
netstat -a -b
..will show you which exe 'owns' a port.
In PowerShell, Get-NetworkStatistics:
#dot source the script (or add to your profile or a custom module):
. "\\path\to\Get-NetworkStatistics.ps1"
#Run Get-NetworkStatistics against exampleComputer, format results in an autosized table
Get-NetworkStatistics -computername exampleComputer | Format-Table -autosize
#Get help on Get-NetworkStatistics
Get-Help Get-NetworkStatistics -Full
#Run get-networkstatistics against k-it-thin-02. Show only results for the Chrome process. If possible, show host names rather than IP addresses. Format in a table.
Get-NetworkStatistics chrome -computername k-it-thin-02 -ShowHostNames | Format-Table
#Get all processes in the listening state using TCP
Get-NetworkStatistics -State LISTENING -Protocol tcp
Code for Get-NetworkStatistics.ps1 below:
function Get-NetworkStatistics {
<#
.SYNOPSIS
Display current TCP/IP connections for local or remote system
.FUNCTIONALITY
Computers
.DESCRIPTION
Display current TCP/IP connections for local or remote system. Includes the process ID (PID) and process name for each connection.
If the port is not yet established, the port number is shown as an asterisk (*).
.PARAMETER ProcessName
Gets connections by the name of the process. The default value is '*'.
.PARAMETER Port
The port number of the local computer or remote computer. The default value is '*'.
.PARAMETER Address
Gets connections by the IP address of the connection, local or remote. Wildcard is supported. The default value is '*'.
.PARAMETER Protocol
The name of the protocol (TCP or UDP). The default value is '*' (all)
.PARAMETER State
Indicates the state of a TCP connection. The possible states are as follows:
Closed - The TCP connection is closed.
Close_Wait - The local endpoint of the TCP connection is waiting for a connection termination request from the local user.
Closing - The local endpoint of the TCP connection is waiting for an acknowledgement of the connection termination request sent previously.
Delete_Tcb - The transmission control buffer (TCB) for the TCP connection is being deleted.
Established - The TCP handshake is complete. The connection has been established and data can be sent.
Fin_Wait_1 - The local endpoint of the TCP connection is waiting for a connection termination request from the remote endpoint or for an acknowledgement of the connection termination request sent previously.
Fin_Wait_2 - The local endpoint of the TCP connection is waiting for a connection termination request from the remote endpoint.
Last_Ack - The local endpoint of the TCP connection is waiting for the final acknowledgement of the connection termination request sent previously.
Listen - The local endpoint of the TCP connection is listening for a connection request from any remote endpoint.
Syn_Received - The local endpoint of the TCP connection has sent and received a connection request and is waiting for an acknowledgment.
Syn_Sent - The local endpoint of the TCP connection has sent the remote endpoint a segment header with the synchronize (SYN) control bit set and is waiting for a matching connection request.
Time_Wait - The local endpoint of the TCP connection is waiting for enough time to pass to ensure that the remote endpoint received the acknowledgement of its connection termination request.
Unknown - The TCP connection state is unknown.
Values are based on the TcpState Enumeration:
http://msdn.microsoft.com/en-us/library/system.net.networkinformation.tcpstate%28VS.85%29.aspx
Cookie Monster - modified these to match netstat output per here:
http://support.microsoft.com/kb/137984
.PARAMETER ComputerName
If defined, run this command on a remote system via WMI. \\computername\c$\netstat.txt is created on that system and the results returned here
.PARAMETER ShowHostNames
If specified, will attempt to resolve local and remote addresses.
.PARAMETER tempFile
Temporary file to store results on remote system. Must be relative to remote system (not a file share). Default is "C:\netstat.txt"
.PARAMETER AddressFamily
Filter by IP Address family: IPv4, IPv6, or the default, * (both).
If specified, we display any result where both the localaddress and the remoteaddress is in the address family.
.EXAMPLE
Get-NetworkStatistics | Format-Table
.EXAMPLE
Get-NetworkStatistics iexplore -computername k-it-thin-02 -ShowHostNames | Format-Table
.EXAMPLE
Get-NetworkStatistics -ProcessName md* -Protocol tcp
.EXAMPLE
Get-NetworkStatistics -Address 192* -State LISTENING
.EXAMPLE
Get-NetworkStatistics -State LISTENING -Protocol tcp
.EXAMPLE
Get-NetworkStatistics -Computername Computer1, Computer2
.EXAMPLE
'Computer1', 'Computer2' | Get-NetworkStatistics
.OUTPUTS
System.Management.Automation.PSObject
.NOTES
Author: Shay Levy, code butchered by Cookie Monster
Shay's Blog: http://PowerShay.com
Cookie Monster's Blog: http://ramblingcookiemonster.github.io/
.LINK
http://gallery.technet.microsoft.com/scriptcenter/Get-NetworkStatistics-66057d71
#>
[OutputType('System.Management.Automation.PSObject')]
[CmdletBinding()]
param(
[Parameter(Position=0)]
[System.String]$ProcessName='*',
[Parameter(Position=1)]
[System.String]$Address='*',
[Parameter(Position=2)]
$Port='*',
[Parameter(Position=3,
ValueFromPipeline = $True,
ValueFromPipelineByPropertyName = $True)]
[System.String[]]$ComputerName=$env:COMPUTERNAME,
[ValidateSet('*','tcp','udp')]
[System.String]$Protocol='*',
[ValidateSet('*','Closed','Close_Wait','Closing','Delete_Tcb','DeleteTcb','Established','Fin_Wait_1','Fin_Wait_2','Last_Ack','Listening','Syn_Received','Syn_Sent','Time_Wait','Unknown')]
[System.String]$State='*',
[switch]$ShowHostnames,
[switch]$ShowProcessNames = $true,
[System.String]$TempFile = "C:\netstat.txt",
[validateset('*','IPv4','IPv6')]
[string]$AddressFamily = '*'
)
begin{
#Define properties
$properties = 'ComputerName','Protocol','LocalAddress','LocalPort','RemoteAddress','RemotePort','State','ProcessName','PID'
#store hostnames in array for quick lookup
$dnsCache = #{}
}
process{
foreach($Computer in $ComputerName) {
#Collect processes
if($ShowProcessNames){
Try {
$processes = Get-Process -ComputerName $Computer -ErrorAction stop | select name, id
}
Catch {
Write-warning "Could not run Get-Process -computername $Computer. Verify permissions and connectivity. Defaulting to no ShowProcessNames"
$ShowProcessNames = $false
}
}
#Handle remote systems
if($Computer -ne $env:COMPUTERNAME){
#define command
[string]$cmd = "cmd /c c:\windows\system32\netstat.exe -ano >> $tempFile"
#define remote file path - computername, drive, folder path
$remoteTempFile = "\\{0}\{1}`${2}" -f "$Computer", (split-path $tempFile -qualifier).TrimEnd(":"), (Split-Path $tempFile -noqualifier)
#delete previous results
Try{
$null = Invoke-WmiMethod -class Win32_process -name Create -ArgumentList "cmd /c del $tempFile" -ComputerName $Computer -ErrorAction stop
}
Catch{
Write-Warning "Could not invoke create win32_process on $Computer to delete $tempfile"
}
#run command
Try{
$processID = (Invoke-WmiMethod -class Win32_process -name Create -ArgumentList $cmd -ComputerName $Computer -ErrorAction stop).processid
}
Catch{
#If we didn't run netstat, break everything off
Throw $_
Break
}
#wait for process to complete
while (
#This while should return true until the process completes
$(
try{
get-process -id $processid -computername $Computer -ErrorAction Stop
}
catch{
$FALSE
}
)
) {
start-sleep -seconds 2
}
#gather results
if(test-path $remoteTempFile){
Try {
$results = Get-Content $remoteTempFile | Select-String -Pattern '\s+(TCP|UDP)'
}
Catch {
Throw "Could not get content from $remoteTempFile for results"
Break
}
Remove-Item $remoteTempFile -force
}
else{
Throw "'$tempFile' on $Computer converted to '$remoteTempFile'. This path is not accessible from your system."
Break
}
}
else{
#gather results on local PC
$results = netstat -ano | Select-String -Pattern '\s+(TCP|UDP)'
}
#initialize counter for progress
$totalCount = $results.count
$count = 0
#Loop through each line of results
foreach($result in $results) {
$item = $result.line.split(' ',[System.StringSplitOptions]::RemoveEmptyEntries)
if($item[1] -notmatch '^\[::'){
#parse the netstat line for local address and port
if (($la = $item[1] -as [ipaddress]).AddressFamily -eq 'InterNetworkV6'){
$localAddress = $la.IPAddressToString
$localPort = $item[1].split('\]:')[-1]
}
else {
$localAddress = $item[1].split(':')[0]
$localPort = $item[1].split(':')[-1]
}
#parse the netstat line for remote address and port
if (($ra = $item[2] -as [ipaddress]).AddressFamily -eq 'InterNetworkV6'){
$remoteAddress = $ra.IPAddressToString
$remotePort = $item[2].split('\]:')[-1]
}
else {
$remoteAddress = $item[2].split(':')[0]
$remotePort = $item[2].split(':')[-1]
}
#Filter IPv4/IPv6 if specified
if($AddressFamily -ne "*")
{
if($AddressFamily -eq 'IPv4' -and $localAddress -match ':' -and $remoteAddress -match ':|\*' )
{
#Both are IPv6, or ipv6 and listening, skip
Write-Verbose "Filtered by AddressFamily:`n$result"
continue
}
elseif($AddressFamily -eq 'IPv6' -and $localAddress -notmatch ':' -and ( $remoteAddress -notmatch ':' -or $remoteAddress -match '*' ) )
{
#Both are IPv4, or ipv4 and listening, skip
Write-Verbose "Filtered by AddressFamily:`n$result"
continue
}
}
#parse the netstat line for other properties
$procId = $item[-1]
$proto = $item[0]
$status = if($item[0] -eq 'tcp') {$item[3]} else {$null}
#Filter the object
if($remotePort -notlike $Port -and $localPort -notlike $Port){
write-verbose "remote $Remoteport local $localport port $port"
Write-Verbose "Filtered by Port:`n$result"
continue
}
if($remoteAddress -notlike $Address -and $localAddress -notlike $Address){
Write-Verbose "Filtered by Address:`n$result"
continue
}
if($status -notlike $State){
Write-Verbose "Filtered by State:`n$result"
continue
}
if($proto -notlike $Protocol){
Write-Verbose "Filtered by Protocol:`n$result"
continue
}
#Display progress bar prior to getting process name or host name
Write-Progress -Activity "Resolving host and process names"`
-Status "Resolving process ID $procId with remote address $remoteAddress and local address $localAddress"`
-PercentComplete (( $count / $totalCount ) * 100)
#If we are running showprocessnames, get the matching name
if($ShowProcessNames -or $PSBoundParameters.ContainsKey -eq 'ProcessName'){
#handle case where process spun up in the time between running get-process and running netstat
if($procName = $processes | Where {$_.id -eq $procId} | select -ExpandProperty name ){ }
else {$procName = "Unknown"}
}
else{$procName = "NA"}
if($procName -notlike $ProcessName){
Write-Verbose "Filtered by ProcessName:`n$result"
continue
}
#if the showhostnames switch is specified, try to map IP to hostname
if($showHostnames){
$tmpAddress = $null
try{
if($remoteAddress -eq "127.0.0.1" -or $remoteAddress -eq "0.0.0.0"){
$remoteAddress = $Computer
}
elseif($remoteAddress -match "\w"){
#check with dns cache first
if ($dnsCache.containskey( $remoteAddress)) {
$remoteAddress = $dnsCache[$remoteAddress]
write-verbose "using cached REMOTE '$remoteAddress'"
}
else{
#if address isn't in the cache, resolve it and add it
$tmpAddress = $remoteAddress
$remoteAddress = [System.Net.DNS]::GetHostByAddress("$remoteAddress").hostname
$dnsCache.add($tmpAddress, $remoteAddress)
write-verbose "using non cached REMOTE '$remoteAddress`t$tmpAddress"
}
}
}
catch{ }
try{
if($localAddress -eq "127.0.0.1" -or $localAddress -eq "0.0.0.0"){
$localAddress = $Computer
}
elseif($localAddress -match "\w"){
#check with dns cache first
if($dnsCache.containskey($localAddress)){
$localAddress = $dnsCache[$localAddress]
write-verbose "using cached LOCAL '$localAddress'"
}
else{
#if address isn't in the cache, resolve it and add it
$tmpAddress = $localAddress
$localAddress = [System.Net.DNS]::GetHostByAddress("$localAddress").hostname
$dnsCache.add($localAddress, $tmpAddress)
write-verbose "using non cached LOCAL '$localAddress'`t'$tmpAddress'"
}
}
}
catch{ }
}
#Write the object
New-Object -TypeName PSObject -Property #{
ComputerName = $Computer
PID = $procId
ProcessName = $procName
Protocol = $proto
LocalAddress = $localAddress
LocalPort = $localPort
RemoteAddress =$remoteAddress
RemotePort = $remotePort
State = $status
} | Select-Object -Property $properties
#Increment the progress counter
$count++
}
}
}
}
}

get IPv4 address into a variable

Is there an easy way in PowerShell 3.0 on Windows 7 to get the local computer's IPv4 address into a variable?
Here is another solution:
$env:HostIP = (
Get-NetIPConfiguration |
Where-Object {
$_.IPv4DefaultGateway -ne $null -and
$_.NetAdapter.Status -ne "Disconnected"
}
).IPv4Address.IPAddress
How about this? (not my real IP Address!)
PS C:\> $ipV4 = Test-Connection -ComputerName (hostname) -Count 1 | Select IPV4Address
PS C:\> $ipV4
IPV4Address
-----------
192.0.2.0
Note that using localhost would just return and IP of 127.0.0.1
PS C:\> $ipV4 = Test-Connection -ComputerName localhost -Count 1 | Select IPV4Address
PS C:\> $ipV4
IPV4Address
-----------
127.0.0.1
The IP Address object has to be expanded out to get the address string
PS C:\> $ipV4 = Test-Connection -ComputerName (hostname) -Count 1 | Select -ExpandProperty IPV4Address
PS C:\> $ipV4
Address : 556228818
AddressFamily : InterNetwork
ScopeId :
IsIPv6Multicast : False
IsIPv6LinkLocal : False
IsIPv6SiteLocal : False
IsIPv6Teredo : False
IsIPv4MappedToIPv6 : False
IPAddressToString : 192.0.2.0
PS C:\> $ipV4.IPAddressToString
192.0.2.0
If I use the machine name this works. But is kind of like a hack (because I am just picking the first value of ipv4 address that I get.)
$ipaddress=([System.Net.DNS]::GetHostAddresses('PasteMachineNameHere')|Where-Object {$_.AddressFamily -eq "InterNetwork"} | select-object IPAddressToString)[0].IPAddressToString
Note that you have to replace the value PasteMachineNameHere in the above expression
This works too
$localIpAddress=((ipconfig | findstr [0-9].\.)[0]).Split()[-1]
Here are three methods using windows powershell and/or powershell core, listed from fastest to slowest.
You can assign it to a variable of your choosing.
Method 1: (this method is the fastest and works in both windows powershell and powershell core)
$ipAddress = (Get-NetIPAddress | Where-Object {$_.AddressState -eq "Preferred" -and $_.ValidLifetime -lt "24:00:00"}).IPAddress
Method 2: (this method is as fast as method 1 but it does not work with powershell core)
$ipAddress = (Test-Connection -ComputerName (hostname) -Count 1 | Select -ExpandProperty IPv4Address).IPAddressToString
Method 3: (although the slowest, it works on both windows powershell and powershell core)
$ipAddress = (Get-NetIPConfiguration | Where-Object {$_.IPv4DefaultGateway -ne $null -and $_.NetAdapter.status -ne "Disconnected"}).IPv4Address.IPAddress
Here is what I ended up using
$ipaddress = $(ipconfig | where {$_ -match 'IPv4.+\s(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' } | out-null; $Matches[1])
which breaks down as
execute ipconfig command - get all the network interface information
use powershell's where filter with a regular expression
regular expression finds the line with "IPv4" and a set of 4 blocks each with 1-3 digits separated by periods, i.e. a v4 IP address
disregard the output by piping it to null
finally get the first matched group as defined by the brackets in the regular expression.
catch that output in $ipaddress for later use.
(Get-WmiObject -Class Win32_NetworkAdapterConfiguration | where {$_.DHCPEnabled -ne $null -and $_.DefaultIPGateway -ne $null}).IPAddress
This one liner gives you the IP address:
(Test-Connection -ComputerName $env:computername -count 1).ipv4address.IPAddressToString
Include it in a Variable?
$IPV4=(Test-Connection -ComputerName $env:computername -count 1).ipv4address.IPAddressToString
Another variant using $env environment variable to grab hostname:
Test-Connection -ComputerName $env:computername -count 1 | Select-Object IPV4Address
or if you just want the IP address returned without the property header
(Test-Connection -ComputerName $env:computername -count 1).IPV4Address.ipaddressTOstring
tldr;
I used this command to get the ip address of my Ethernet network adapter into a variable called IP.
for /f "tokens=3 delims=: " %i in ('netsh interface ip show config name^="Ethernet" ^| findstr "IP Address"') do set IP=%i
For those who are curious to know what all that means, read on
Most commands using ipconfig for example just print out all your IP addresses and I needed a specific one which in my case was for my Ethernet network adapter.
You can see your list of network adapters by using the netsh interface ipv4 show interfaces command. Most people need Wi-Fi or Ethernet.
You'll see a table like so in the output to the command prompt:
Idx Met MTU State Name
--- ---------- ---------- ------------ ---------------------------
1 75 4294967295 connected Loopback Pseudo-Interface 1
15 25 1500 connected Ethernet
17 5000 1500 connected vEthernet (Default Switch)
32 15 1500 connected vEthernet (DockerNAT)
In the name column you should find the network adapter you want (i.e. Ethernet, Wi-Fi etc.).
As mentioned, I was interested in Ethernet in my case.
To get the IP for that adapter we can use the netsh command:
netsh interface ip show config name="Ethernet"
This gives us this output:
Configuration for interface "Ethernet"
DHCP enabled: Yes
IP Address: 169.252.27.59
Subnet Prefix: 169.252.0.0/16 (mask 255.255.0.0)
InterfaceMetric: 25
DNS servers configured through DHCP: None
Register with which suffix: Primary only
WINS servers configured through DHCP: None
(I faked the actual IP number above for security reasons 😉)
I can further specify which line I want using the findstr command in the ms-dos command prompt.
Here I want the line containing the string IP Address.
netsh interface ip show config name="Ethernet" | findstr "IP Address"
This gives the following output:
IP Address: 169.252.27.59
I can then use the for command that allows me to parse files (or multiline strings in this case) and split out the strings' contents based on a delimiter and the item number that I'm interested in.
Note that I am looking for the third item (tokens=3) and that I am using the space character and : as my delimiters (delims=: ).
for /f "tokens=3 delims=: " %i in ('netsh interface ip show config name^="Ethernet" ^| findstr "IP Address"') do set IP=%i
Each value or token in the loop is printed off as the variable %i but I'm only interested in the third "token" or item (hence tokens=3). Note that I had to escape the | and = using a ^
At the end of the for command you can specify a command to run with the content that is returned. In this case I am using set to assign the value to an environment variable called IP. If you want you could also just echo the value or what ever you like.
With that you get an environment variable with the IP Address of your preferred network adapter assigned to an environment variable. Pretty neat, huh?
If you have any ideas for improving please leave a comment.
I was looking for the same thing and figured this out:
$ip = Get-NetIPAddress -AddressFamily IPv4 -InterfaceIndex $(Get-NetConnectionProfile | Select-Object -ExpandProperty InterfaceIndex) | Select-Object -ExpandProperty IPAddress
This filters out both the loopback address and some virtual networks I have.
$ip = (Get-NetIPAddress -AddressFamily IPv4 -InterfaceIndex $(Get-NetConnectionProfile).InterfaceIndex).IPAddress
OR
function Get-LocalIP {
(
Get-NetIPAddress `
-AddressFamily IPv4 `
-InterfaceIndex $(
Get-NetConnectionProfile
).InterfaceIndex
).IPAddress
}
$ip = Get-LocalIP
To grab the device's IPv4 addresses, and filter to only grab ones that match your scheme (i.e. Ignore and APIPA addresses or the LocalHost address). You could say to grab the address matching 192.168.200.* for example.
$IPv4Addr = Get-NetIPAddress -AddressFamily ipV4 | where {$_.IPAddress -like X.X.X.X} | Select IPAddress
# Patrick Burwell's Ping Script - Patrick.Burwell#Infosys.com #
$Output= #() #sets an array
$names = Get-Content ".\input\ptd.pc_list.txt" #sets a list to use, like a DNS dump
foreach ($name in $names){ #sets the input by enumerating a text file to loop through and sets a variable to execute against
if ($IPV4 = Test-Connection -Delay 15 -ComputerName $name -Count 1 -ErrorAction SilentlyContinue|select IPV4Address #run ping and sets only IPV4Address response variable
){# If true then run...
$Output+= $Name,($IPV4.IPV4Address).IPAddressToString # Fills the array with the #true response
Write-Host $Name',','Ping,'($IPV4.IPV4Address).IPAddressToString -ForegroundColor Green #Sets the output to receive the Name, result and IPV4Address and prints the reply to the console with specific colors
}
else{#If false then run...
$Output+= "$name," #Fills the array with the #false response
Write-Host "$Name," -ForegroundColor Red #Prints the reply to the console with specific colors
}
}
#$Output | Out-file ".\output\result.csv" #<-- use to export to a text file (Set path as needed)
#$Output | Export-CSV ".\output\result.csv" -NoTypeInformation #<-- use to export to a csv file (Set path as needed)
#If you choose, you can merely have the reply by the name and IP, and the Name and no IP by removing the Ping comments
As I was working in Powershell 3, none of the answers here worked for me. It's based on Rob's approach, but this one works when you have multiple network adapters, it also picks out the IP correctly using capture groups
function GetIPConfig {
return ipconfig | select-string ('(\s)+IPv4.+\s(?<IP>(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}))(\s)*') -AllMatches | %{ $_.Matches } | % { $_.Groups["IP"]} | %{ $_.Value }
}
Non of the top comments are actually fully correct since a computer can have multiple interfaces and an interface can have multiple IP addresses. There are a few answers here which technically correct but utilizes "funky" ways to filter out wellknown addresses (like APIPA, localhost, etc) whereas even Powershell 3.0 have a native way to do so with PrefixOrigin.
$IPv4Addresses = $(Get-NetIPAddress | Where-Object { $_.PrefixOrigin -ne "WellKnown" -and $_.AddressFamily -eq "IPv4" }).IPAddress
I do this :
$interFaceAliasName="LAN" # You have to change the name according to your interface's name
$myInterface=(Get-NetIPAddress -InterfaceAlias $interFaceAliasName)
$myIP=$myInterface.IPv4Address
I recently had the same issue. So I wrote a script to parse it from the ipconfig /all output. This script is easily modifiable to obtain any of the parameters of the interfaces and it works on Windows 7 also.
Get output of IP config in LineNumber | Line format
$ip_config = $(ipconfig /all | % {$_ -split "rn"} | Select-String -Pattern ".*" | select LineNumber, Line)
Get list of interfaces (+ last line of ipconfig output) in LineNumber | Line format
$interfaces = $($ip_config | where {$_.Line -notmatch '^\s*$'} | where {$_.Line -notmatch '^\s'}) + $($ip_config | Select -last 1)
Filter through the interfaces list for the specific interface you want
$LAN = $($interfaces | where {$_.Line -match 'Wireless Network Connection:$'})
Get the start and end line numbers of chosen interface from output
$i = $interfaces.IndexOf($LAN)
$start = $LAN.LineNumber
$end = $interfaces[$i+1].LineNumber
Pick the lines from start..end
$LAN = $ip_config | where {$_.LineNumber -in ($start..$end)}
Get IP(v4) address field (returns null if no IPv4 address present)
$LAN_IP = #($LAN | where {$_ -match 'IPv4.+:\s(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'})
$LAN_IP = &{If ($LAN_IP.Count -gt 0) {$Matches[1]} Else {$null}}
$a = ipconfig
$result = $a[8] -replace "IPv4 Address. . . . . . . . . . . :",""
Also check which index of ipconfig has the IPv4 Address

How to run internal Powershell script function from cmd.exe with arguments

I want to use a powershell (.ps1) script in the command prompt without using this commands
Powershell.exe -noexit Set-ExecutionPolicy Unrestricted -file "C:\Get-NetworkStatistics.ps1"
Currently this command opens powershell windows. I want direct cmd to use this script and giving me output. Is it possible?
Below is my Get-NetworkStatistics.ps1 script. please guide me is there any way to use it directly?
function Get-NetworkStatistics {
<#
.SYNOPSIS
Display current TCP/IP connections for local or remote system
.FUNCTIONALITY
Computers
.DESCRIPTION
Display current TCP/IP connections for local or remote system. Includes the process ID (PID) and process name for each connection.
If the port is not yet established, the port number is shown as an asterisk (*).
.PARAMETER ProcessName
Gets connections by the name of the process. The default value is '*'.
.PARAMETER Port
The port number of the local computer or remote computer. The default value is '*'.
.PARAMETER Address
Gets connections by the IP address of the connection, local or remote. Wildcard is supported. The default value is '*'.
.PARAMETER Protocol
The name of the protocol (TCP or UDP). The default value is '*' (all)
.PARAMETER State
Indicates the state of a TCP connection. The possible states are as follows:
Closed - The TCP connection is closed.
Close_Wait - The local endpoint of the TCP connection is waiting for a connection termination request from the local user.
Closing - The local endpoint of the TCP connection is waiting for an acknowledgement of the connection termination request sent previously.
Delete_Tcb - The transmission control buffer (TCB) for the TCP connection is being deleted.
Established - The TCP handshake is complete. The connection has been established and data can be sent.
Fin_Wait_1 - The local endpoint of the TCP connection is waiting for a connection termination request from the remote endpoint or for an acknowledgement of the connection termination request sent previously.
Fin_Wait_2 - The local endpoint of the TCP connection is waiting for a connection termination request from the remote endpoint.
Last_Ack - The local endpoint of the TCP connection is waiting for the final acknowledgement of the connection termination request sent previously.
Listen - The local endpoint of the TCP connection is listening for a connection request from any remote endpoint.
Syn_Received - The local endpoint of the TCP connection has sent and received a connection request and is waiting for an acknowledgment.
Syn_Sent - The local endpoint of the TCP connection has sent the remote endpoint a segment header with the synchronize (SYN) control bit set and is waiting for a matching connection request.
Time_Wait - The local endpoint of the TCP connection is waiting for enough time to pass to ensure that the remote endpoint received the acknowledgement of its connection termination request.
Unknown - The TCP connection state is unknown.
Values are based on the TcpState Enumeration:
http://msdn.microsoft.com/en-us/library/system.net.networkinformation.tcpstate%28VS.85%29.aspx
Cookie Monster - modified these to match netstat output per here:
http://support.microsoft.com/kb/137984
.PARAMETER ComputerName
If defined, run this command on a remote system via WMI. \\computername\c$\netstat.txt is created on that system and the results returned here
.PARAMETER ShowHostNames
If specified, will attempt to resolve local and remote addresses.
.PARAMETER tempFile
Temporary file to store results on remote system. Must be relative to remote system (not a file share). Default is "C:\netstat.txt"
.EXAMPLE
Get-NetworkStatistics | Format-Table
.EXAMPLE
Get-NetworkStatistics iexplore -computername k-it-thin-02 -ShowHostNames | Format-Table
.EXAMPLE
Get-NetworkStatistics -ProcessName md* -Protocol tcp
.EXAMPLE
Get-NetworkStatistics -Address 192* -State LISTENING
.EXAMPLE
Get-NetworkStatistics -State LISTENING -Protocol tcp
.OUTPUTS
System.Management.Automation.PSObject
.NOTES
Author: Shay Levy, code butchered by Cookie Monster
Shay's Blog: http://PowerShay.com
Cookie Monster's Blog: http://ramblingcookiemonster.wordpress.com
.LINK
http://gallery.technet.microsoft.com/scriptcenter/Get-NetworkStatistics-66057d71
#>
[OutputType('System.Management.Automation.PSObject')]
[CmdletBinding(DefaultParameterSetName='name')]
param(
[Parameter(Position=0, ValueFromPipeline=$true,ParameterSetName='name')]
[System.String]$ProcessName='*',
[Parameter(Position=0, ValueFromPipeline=$true,ParameterSetName='address')]
[System.String]$Address='*',
[Parameter(ValueFromPipeline=$true,ParameterSetName='port')]
$Port='*',
[Parameter()]
[ValidateSet('*','tcp','udp')]
[System.String]$Protocol='*',
[Parameter()]
[ValidateSet('*','Closed','Close_Wait','Closing','Delete_Tcb','DeleteTcb','Established','Fin_Wait_1','Fin_Wait_2','Last_Ack','Listening','Syn_Received','Syn_Sent','Time_Wait','Unknown')]
[System.String]$State='*',
[Parameter(ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
[validatescript({test-connection -count 2 -buffersize 16 -quiet -ComputerName $_})]
[System.String]$computername=$env:COMPUTERNAME,
[switch]$ShowHostnames,
[switch]$ShowProcessNames = $true,
[System.String]$tempFile = "C:\netstat.txt"
)
begin{
#Define properties
$properties = 'Protocol','LocalAddress','LocalPort','RemoteAddress','RemotePort','State','ProcessName','PID'
#Collect processes
if($ShowProcessNames){
Try {
$processes = get-process -computername $computername -ErrorAction stop | select name, id
}
Catch {
Write-warning "Could not run Get-Process -computername $computername. Verify permissions and connectivity. Defaulting to no ShowProcessNames"
$ShowProcessNames = $false
}
}
#store hostnames in array for quick lookup
$dnsCache = #()
}
process{
#Handle remote systems
if($computername -ne $env:COMPUTERNAME){
#define command
[string]$cmd = "cmd /c c:\windows\system32\netstat.exe -ano >> $tempFile"
#define remote file path - computername, drive, folder path
$remoteTempFile = "\\{0}\{1}`${2}" -f "$computername", (split-path $tempFile -qualifier).TrimEnd(":"), (Split-Path $tempFile -noqualifier)
#delete previous results
Try{
$null = Invoke-WmiMethod -class Win32_process -name Create -ArgumentList "cmd /c del $tempFile" -ComputerName $computername -ErrorAction stop
}
Catch{
Write-Warning "Could not invoke create win32_process on $computername to delete $tempfile"
}
#run command
Try{
$processID = (Invoke-WmiMethod -class Win32_process -name Create -ArgumentList $cmd -ComputerName $computername -ErrorAction stop).processid
}
Catch{
#If we didn't run netstat, break everything off
Throw $_
Break
}
#wait for process to complete
while (
#This while should return true until the process completes
$(
try{
get-process -id $processid -computername $computername -ErrorAction Stop
}
catch{
$FALSE
}
)
) {
start-sleep -seconds 2
}
#gather results
if(test-path $remoteTempFile){
Try {
$results = Get-Content $remoteTempFile | Select-String -Pattern '\s+(TCP|UDP)'
}
Catch {
Throw "Could not get content from $remoteTempFile for results"
Break
}
Remove-Item $remoteTempFile -force
}
else{
Throw "'$tempFile' on $computername converted to '$remoteTempFile'. This path is not accessible from your system."
Break
}
}
else{
#gather results on local PC
$results = netstat -ano | Select-String -Pattern '\s+(TCP|UDP)'
}
#initialize counter for progress
$totalCount = $results.count
$count = 0
#Loop through each line of results
foreach($result in $results) {
$item = $result.line.split(' ',[System.StringSplitOptions]::RemoveEmptyEntries)
if($item[1] -notmatch '^\[::'){
#parse the netstat line for local address and port
if (($la = $item[1] -as [ipaddress]).AddressFamily -eq 'InterNetworkV6'){
$localAddress = $la.IPAddressToString
$localPort = $item[1].split('\]:')[-1]
}
else {
$localAddress = $item[1].split(':')[0]
$localPort = $item[1].split(':')[-1]
}
#parse the netstat line for remote address and port
if (($ra = $item[2] -as [ipaddress]).AddressFamily -eq 'InterNetworkV6'){
$remoteAddress = $ra.IPAddressToString
$remotePort = $item[2].split('\]:')[-1]
}
else {
$remoteAddress = $item[2].split(':')[0]
$remotePort = $item[2].split(':')[-1]
}
#parse the netstat line for other properties
$procId = $item[-1]
$proto = $item[0]
$status = if($item[0] -eq 'tcp') {$item[3]} else {$null}
#Display progress bar prior to getting process name or host name
Write-Progress -Activity "Resolving host and process names"`
-Status "Resolving process ID $procId with remote address $remoteAddress and local address $localAddress"`
-PercentComplete (( $count / $totalCount ) * 100)
#If we are running showprocessnames, get the matching name
if($ShowProcessNames){
#handle case where process spun up in the time between running get-process and running netstat
if($procName = $processes | ?{$_.id -eq $procId} | select -ExpandProperty name ){ }
else {$procName = "Unknown"}
}
else{$procName = "NA"}
#if the showhostnames switch is specified, try to map IP to hostname
if($showHostnames){
$tmpAddress = $null
try{
if($remoteAddress -eq "127.0.0.1" -or $remoteAddress -eq "0.0.0.0"){
$remoteAddress = $computername
}
elseif($remoteAddress -match "\w"){
#check with dns cache first
if($tmpAddress = $dnsCache -match "`t$remoteAddress$"){
$remoteAddress = ( $tmpAddress -split "`t" )[0]
write-verbose "using cached REMOTE '$tmpADDRESS'"
}
else{
#if address isn't in the cache, resolve it and add it
$tmpAddress = $remoteAddress
$remoteAddress = [System.Net.DNS]::GetHostByAddress("$remoteAddress").hostname
$dnsCache += "$remoteAddress`t$tmpAddress"
write-verbose "using non cached REMOTE '$remoteAddress`t$tmpAddress"
}
}
}
catch{ }
try{
if($localAddress -eq "127.0.0.1" -or $localAddress -eq "0.0.0.0"){
$localAddress = $computername
}
elseif($localAddress -match "\w"){
#check with dns cache first
if($tmpAddress = $dnsCache -match "`t$localAddress$"){
$localAddress = ( $tmpAddress -split "`t" )[0]
write-verbose "using cached LOCAL '$tmpADDRESS'"
}
else{
#if address isn't in the cache, resolve it and add it
$tmpAddress = $localAddress
$localAddress = [System.Net.DNS]::GetHostByAddress("$localAddress").hostname
$dnsCache += "$localAddress`t$tmpAddress"
write-verbose "using non cached LOCAL '$localAddress'`t'$tmpAddress'"
}
}
}
catch{ }
}
#Define the object
$pso = New-Object -TypeName PSObject -Property #{
PID = $procId
ProcessName = $procName
Protocol = $proto
LocalAddress = $localAddress
LocalPort = $localPort
RemoteAddress =$remoteAddress
RemotePort = $remotePort
State = $status
} | Select-Object -Property $properties
#Filter and display the object
if($PSCmdlet.ParameterSetName -eq 'port'){
if($pso.RemotePort -like $Port -or $pso.LocalPort -like $Port){
if($pso.Protocol -like $Protocol -and $pso.State -like $State){
$pso
}
}
}
if($PSCmdlet.ParameterSetName -eq 'address'){
if($pso.RemoteAddress -like $Address -or $pso.LocalAddress -like $Address){
if($pso.Protocol -like $Protocol -and $pso.State -like $State){
$pso
}
}
}
if($PSCmdlet.ParameterSetName -eq 'name'){
if($pso.ProcessName -like $ProcessName){
if($pso.Protocol -like $Protocol -and $pso.State -like $State){
$pso
}
}
}
#Increment the progress counter
$count++
}
}
}
}
Dito to what #Kayasax said so picturesquely - you cannot run a powershell script without powershell, period. An alternative to your command is the following, executes and exits:
#powershell C:\Get-NetworkStatistics.ps1
In response to your comment, "...my main purpose it to run this function Get-NetworkStatistics -computername Gbi1 | Format-Table -autosize..."
You can add these two lines to the end of Get-NetworkStatistics.ps1
(This is a hack to get your purpose met, negates most of the power of Shay's script):
$ARG_COMPNAME = $args[0]
Get-NetworkStatistics -computername $ARG_COMPNAME | Format-Table -autosize
Then you call the Powershell script along the lines of:
C:\>powershell.exe -noprofile -file Get-NetworkStatistics.ps1 Gbi1
The script runs and dumps a netstat table to screen and dumps a file c:\netstat.txt

Powershell - Capture socket and process

I am trying this small powershell script to look for netstat -ano output every five seconds and then filter only outgoing connections on port 80 on any IP address, plus catch the related process that opened the socket.
I think the problem here is if there are multiple entries in the output then it cannot handle the array. What is missing here? any better way to do this?
while(1) {netstat -ano | ? {$_ -like "*10.10.10.10:* *:80 *"} |
% {
$_ -match "\d+$";
$matches | ForEach-Object {
Get-Process -id $matches[0] | Format-List *;
(Get-Process -id $matches[0]).WaitForExit()
}
Start-Sleep -s 5;
}
}
Shay Levy wrote a function to work with netstat info that might help you filter down your information and outputs it in a manner that would be easier to filter on: How to find running processes and their port number
NOTE: I know most folks probably say to post the code here in the event the page goes missing. Shay is updating this page as things change or for improvements (like adding support for IPv6 connections) so I doubt he will be taking it down anytime soon.
See Get-NetworkStatistics:
> Get-NetworkStatistics | where Localport -eq 8000
ComputerName : DESKTOP-JL59SC6
Protocol : TCP
LocalAddress : 0.0.0.0
LocalPort : 8000
RemoteAddress : 0.0.0.0
RemotePort : 0
State : LISTENING
ProcessName : node
PID : 11552

Resources