find process that is blocking a port on windows - 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++
}
}
}
}
}

Related

Build a script to check-uncheck sharing boxes at Ethernet adapter

We have P2P connection between a host computer and some target,
because of stability issues, the connection sometimes dead, and we need to uncheck "allow other network users to connect through this computer's internet connection" with adding "Home networking connection:" as "p2p" and also uncheck-check the "Allow other network users to control or disable the shared Internet connection" to solve the connection issue.
We don't want to try to find the root cause, we decide to build this workarround.
Here are the steps i want to build a PS script to do:
go to the properties of Ethernet adapter:
Enter properties
uncheck at "Sharing" section this check-box:
un-check
re-check these boxes (at the picture at step 4)
add to "Home networking connection "p2p".
re-check
I tried to build a script that will do this, but, It broke my host and we had to re-build the host after trying running it, please don't run it on your computer:
echo Stability tool...
# High Privilage level script: https://stackoverflow.com/questions/7690994/running-a-command-as-administrator-using-powershell
if (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{
$arguments = "& '" +$myinvocation.mycommand.definition + "'"
Start-Process powershell -Verb runAs -ArgumentList $arguments
Break
}
$ncp = Get-NetConnectionProfile
$ncp.InterfaceAlias
# print the NetAdapters,
# from here: https://devblogs.microsoft.com/scripting/enabling-and-disabling-network-adapters-with-powershell/
Get-NetAdapter
# Enable all the NetAdapters
Get-NetAdapter | ? status -ne up | Enable-NetAdapter
# print all the NetAdapters after making the Disabled\Disconnected ones to up.
Get-NetAdapter
#$wmi = Get-WmiObject -Class Win32_NetworkAdapter -filter "Name LIKE '%Wireless%'"
# from: https://superuser.com/questions/470319/how-to-enable-internet-connection-sharing-using-command-line
foreach ($AdapterName in $ncp.InterfaceAlias)
{
# Register the HNetCfg library (once)
regsvr32 hnetcfg.dll
# Create a NetSharingManager object
$m = New-Object -ComObject HNetCfg.HNetShare
# List connections
$m.EnumEveryConnection |% { $m.NetConnectionProps.Invoke($_) }
# Find connection
$c = $m.EnumEveryConnection |? { $m.NetConnectionProps.Invoke($_).Name -eq $AdapterName }
# Get sharing configuration
$config = $m.INetSharingConfigurationForINetConnection.Invoke($c)
# See if sharing is enabled
Write-Output $config.SharingEnabled
# See the role of connection in sharing
# 0 - public, 1 - private
# Only meaningful if SharingEnabled is True
Write-Output $config.SharingType
# Disable sharing
$config.DisableSharing()
# Enable sharing (0 - public, 1 - private)
$config.EnableSharing(0)
}
# print all the NetAdapters after making the Disabled\Disconnected ones to up.
Get-NetAdapter
I prefer it on PS script but if there is another way to do tyhat automatically - i will glad to hear.
After the using the answer of NeoTheNerd, here is the code i used to build a batch file that do the refresh i ask for (one adapter of 'p2p' ends with disable sharing and the 'Ethernet' adapter finish as shard with Home networking connection to the 'p2p' adapter) - here i will give a full description to build the 4 files that together do the refresh (the copy and move of the files was essential in this project since i download them from a server, here i put them on a local location):
SET TargetDir=c:\Users\mkdahan\Documents\WindowsPowerShell\Functions
set SourceDir=c:\scripts_for_power_shell\Shell_Functions
#echo ******************* all variables were sets **********************
robocopy %SourceDir% %TargetDir% *.* /MIR /IS /R:10 /W:10
rem Step 3:
move %TargetDir%\Microsoft.PowerShell_profile.ps1 C:\Users\mkdahan\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
powershell -Command "Get-MrInternetConnectionSharing P2P"
powershell -Command "Set-MrInternetConnectionSharing -InternetInterfaceName P2P -Enabled $true"
powershell -Command "Set-MrInternetConnectionSharing -InternetInterfaceName P2P -Enabled $false"
powershell -Command "Get-MrInternetConnectionSharing P2P"
echo %time%
timeout 5 > NUL
echo %time%
powershell -Command "if (!(Test-Path (Split-Path $profile))) { mkdir (Split-Path $profile) } ; if (!(Test-Path $profile)) { New-Item $profile -ItemType file }"
powershell -Command "Get-MrInternetConnectionSharing Ethernet, 'p2p'"
powershell -Command "Set-MrInternetConnectionSharing -InternetInterfaceName Ethernet -LocalInterfaceName 'P2P' -Enabled $false"
powershell -Command "Set-MrInternetConnectionSharing -InternetInterfaceName Ethernet -LocalInterfaceName 'P2P' -Enabled $true"
powershell -Command "Get-MrInternetConnectionSharing Ethernet, 'P2P'"
pause
where at the folder: c:\scripts_for_power_shell\Shell_Functions
there are three files with this content:
Get-MrInternetConnectionSharing,ps1:
function Get-MrInternetConnectionSharing {
<#
.SYNOPSIS
Retrieves the status of Internet connection sharing for the specified network adapter(s).
.DESCRIPTION
Get-MrInternetConnectionSharing is an advanced function that retrieves the status of Internet connection sharing
for the specified network adapter(s).
.PARAMETER InternetInterfaceName
The name of the network adapter(s) to check the Internet connection sharing status for.
.EXAMPLE
Get-MrInternetConnectionSharing -InternetInterfaceName Ethernet, 'Internal Virtual Switch'
.EXAMPLE
'Ethernet', 'Internal Virtual Switch' | Get-MrInternetConnectionSharing
.EXAMPLE
Get-NetAdapter | Get-MrInternetConnectionSharing
.INPUTS
String
.OUTPUTS
PSCustomObject
.NOTES
Author: Mike F Robbins
Website: http://mikefrobbins.com
Twitter: #mikefrobbins
#>
[CmdletBinding()]
param (
[Parameter(Mandatory,
ValueFromPipeline,
ValueFromPipelineByPropertyName)]
[Alias('Name')]
[string[]]$InternetInterfaceName
)
BEGIN {
regsvr32.exe /s hnetcfg.dll
$netShare = New-Object -ComObject HNetCfg.HNetShare
}
PROCESS {
foreach ($Interface in $InternetInterfaceName){
$publicConnection = $netShare.EnumEveryConnection |
Where-Object {
$netShare.NetConnectionProps.Invoke($_).Name -eq $Interface
}
try {
$Results = $netShare.INetSharingConfigurationForINetConnection.Invoke($publicConnection)
}
catch {
Write-Warning -Message "An unexpected error has occurred for network adapter: '$Interface'"
Continue
}
[pscustomobject]#{
Name = $Interface
SharingEnabled = $Results.SharingEnabled
SharingConnectionType = $Results.SharingConnectionType
InternetFirewallEnabled = $Results.InternetFirewallEnabled
}
}
}
}
Set-MrInternetConnectionSharing.ps1
function Set-MrInternetConnectionSharing {
<#
.SYNOPSIS
Configures Internet connection sharing for the specified network adapter(s).
.DESCRIPTION
Set-MrInternetConnectionSharing is an advanced function that configures Internet connection sharing
for the specified network adapter(s). The specified network adapter(s) must exist and must be enabled.
To enable Internet connection sharing, Internet connection sharing cannot already be enabled on any
network adapters.
.PARAMETER InternetInterfaceName
The name of the network adapter to enable or disable Internet connection sharing for.
.PARAMETER LocalInterfaceName
The name of the network adapter to share the Internet connection with.
.PARAMETER Enabled
Boolean value to specify whether to enable or disable Internet connection sharing.
.EXAMPLE
Set-MrInternetConnectionSharing -InternetInterfaceName Ethernet -LocalInterfaceName 'Internal Virtual Switch' -Enabled $true
.EXAMPLE
'Ethernet' | Set-MrInternetConnectionSharing -LocalInterfaceName 'Internal Virtual Switch' -Enabled $false
.EXAMPLE
Get-NetAdapter -Name Ethernet | Set-MrInternetConnectionSharing -LocalInterfaceName 'Internal Virtual Switch' -Enabled $true
.INPUTS
String
.OUTPUTS
PSCustomObject
.NOTES
Author: Mike F Robbins
Website: http://mikefrobbins.com
Twitter: #mikefrobbins
#>
[CmdletBinding()]
param (
[Parameter(Mandatory,
ValueFromPipeline,
ValueFromPipelineByPropertyName)]
[ValidateScript({
If ((Get-NetAdapter -Name $_ -ErrorAction SilentlyContinue -OutVariable INetNIC) -and (($INetNIC).Status -ne 'Disabled' -or ($INetNIC).Status -ne 'Not Present')) {
$True
}
else {
Throw "$_ is either not a valid network adapter of it's currently disabled."
}
})]
[Alias('Name')]
[string]$InternetInterfaceName,
[ValidateScript({
If ((Get-NetAdapter -Name $_ -ErrorAction SilentlyContinue -OutVariable LocalNIC) -and (($LocalNIC).Status -ne 'Disabled' -or ($INetNIC).Status -ne 'Not Present')) {
$True
}
else {
Throw "$_ is either not a valid network adapter of it's currently disabled."
}
})]
[string]$LocalInterfaceName,
[Parameter(Mandatory)]
[bool]$Enabled
)
BEGIN {
if ((Get-NetAdapter | Get-MrInternetConnectionSharing).SharingEnabled -contains $true -and $Enabled) {
Write-Warning -Message 'Unable to continue due to Internet connection sharing already being enabled for one or more network adapters.'
Break
}
regsvr32.exe /s hnetcfg.dll
$netShare = New-Object -ComObject HNetCfg.HNetShare
}
PROCESS {
$publicConnection = $netShare.EnumEveryConnection |
Where-Object {
$netShare.NetConnectionProps.Invoke($_).Name -eq $InternetInterfaceName
}
$publicConfig = $netShare.INetSharingConfigurationForINetConnection.Invoke($publicConnection)
if ($PSBoundParameters.LocalInterfaceName) {
$privateConnection = $netShare.EnumEveryConnection |
Where-Object {
$netShare.NetConnectionProps.Invoke($_).Name -eq $LocalInterfaceName
}
$privateConfig = $netShare.INetSharingConfigurationForINetConnection.Invoke($privateConnection)
}
if ($Enabled) {
$publicConfig.EnableSharing(0)
if ($PSBoundParameters.LocalInterfaceName) {
$privateConfig.EnableSharing(1)
}
}
else {
$publicConfig.DisableSharing()
if ($PSBoundParameters.LocalInterfaceName) {
$privateConfig.DisableSharing()
}
}
}
}
Microsoft.PowerShell_profile.ps1:
# Load own custom functions at startup
$OwnFunctionsDir = "C:\Users\LAB_COREIP\Documents\WindowsPowerShell\Functions"
Write-Host "Loading own PowerShell functions from:" -ForegroundColor Green
Write-Host "$OwnFunctionsDir" -ForegroundColor Yellow
Get-ChildItem "$OwnFunctionsDir\*.ps1" | %{.$_}
Write-Host ''
So the 4 files (the batch with the three ps1 files), building a full refresh for the P2P connection, after double click on the batch file.
Thanks a lot NeoTheNerd, Kiran and Bluuf for the help.
To be constructive taking a mish mash of scripts and using them, without applying logic to each individual script is not logical.
If you look at this webpage - Configure Internet Connection Sharing with PowerShell
https://mikefrobbins.com/2017/10/19/configure-internet-connection-sharing-with-powershell/
It steps out what you seek.
Step 1
Use the function Get-MrInternetConnectionSharing to retrieve the current settings
Step 2
Use the Get-MrInternetConnectionSharing function to specify the network adapters used in my Internet connection.
#Requires -Version 3.0
function Get-MrInternetConnectionSharing {
<#
.SYNOPSIS
Retrieves the status of Internet connection sharing for the specified network adapter(s).
.DESCRIPTION
Get-MrInternetConnectionSharing is an advanced function that retrieves the status of Internet connection sharing
for the specified network adapter(s).
.PARAMETER InternetInterfaceName
The name of the network adapter(s) to check the Internet connection sharing status for.
.EXAMPLE
Get-MrInternetConnectionSharing -InternetInterfaceName Ethernet, 'Internal Virtual Switch'
.EXAMPLE
'Ethernet', 'Internal Virtual Switch' | Get-MrInternetConnectionSharing
.EXAMPLE
Get-NetAdapter | Get-MrInternetConnectionSharing
.INPUTS
String
.OUTPUTS
PSCustomObject
.NOTES
Author: Mike F Robbins
Website: http://mikefrobbins.com
Twitter: #mikefrobbins
#>
The script can be found by visiting the url
Step 3
Use the the second function, Set-MrInternetConnectionSharing configures the settings.
#Requires -Version 3.0 -Modules NetAdapter
function Set-MrInternetConnectionSharing {
<#
.SYNOPSIS
Configures Internet connection sharing for the specified network adapter(s).
.DESCRIPTION
Set-MrInternetConnectionSharing is an advanced function that configures Internet connection sharing
for the specified network adapter(s). The specified network adapter(s) must exist and must be enabled.
To enable Internet connection sharing, Internet connection sharing cannot already be enabled on any
network adapters.
.PARAMETER InternetInterfaceName
The name of the network adapter to enable or disable Internet connection sharing for.
.PARAMETER LocalInterfaceName
The name of the network adapter to share the Internet connection with.
.PARAMETER Enabled
Boolean value to specify whether to enable or disable Internet connection sharing.
.EXAMPLE
Set-MrInternetConnectionSharing -InternetInterfaceName Ethernet -LocalInterfaceName 'Internal Virtual Switch' -Enabled $true
.EXAMPLE
'Ethernet' | Set-MrInternetConnectionSharing -LocalInterfaceName 'Internal Virtual Switch' -Enabled $false
.EXAMPLE
Get-NetAdapter -Name Ethernet | Set-MrInternetConnectionSharing -LocalInterfaceName 'Internal Virtual Switch' -Enabled $true
.INPUTS
String
.OUTPUTS
PSCustomObject
.NOTES
Author: Mike F Robbins
Website: http://mikefrobbins.com
Twitter: #mikefrobbins
#>
The script can be found by visiting the url

Adding printer to print Server via powershell

Im wanting to add a printer and its port to the print server only if either that printer name and printer port isn't already taken.
I have this so far
$prnt = Import-Csv C:\scripts\printer.csv
foreach ($printer in $prnt) {
$var = Get-Printer
If (($var.name -contains $printer.Printername) -and ($var.portname -contains
$printer.IPAddress))
{
Write-Host "$printer exist!" -ForegroundColor Blue
}
else
{
Add-PrinterPort -ComputerName Printsrv01 -Name $printer.IPAddress -
PrinterHostAddress $printer.IPAddress
Add-Printer -ComputerName Printsrv01 -Name $printer.Printername -
DriverName $printer.Driver -PortName $printer.IPAddress -Location
$printer.Location
}
}
Problem is mainly with my 'if' statement. It catches the printer name but not the portnumber/ip. (The portnumber is the ip). And I also think my if statement is comparing the whole array of values from the csv file, and not just the specific value in the array like I want. Any help would be appreciated.
Csv file is setup like this
enter image description here
Try this:
$prnt = Import-Csv C:\scripts\printer.csv
$printers = (Get-Printer).Name
$ports = (Get-PrinterPort).PrinterHostAddress
foreach ($printer in $prnt)
{
If (($printers -contains $printer.Printername) -or ($ports -contains $printer.IPAddress))
{
Write-Host "$printer exist!" -ForegroundColor Blue
}
else
{
Add-PrinterPort -ComputerName Printsrv01 -Name $printer.IPAddress -PrinterHostAddress $printer.IPAddress
Add-Printer -ComputerName Printsrv01 -Name $printer.Printername -DriverName $printer.Driver -PortName $printer.IPAddress -Location $printer.Location
}
}

How to read from a text file when adding firewall rules using new-netfirewallrule

I am trying to create a script to read from a text file to which I would like to add firewall rules to each server on a line by line basis.
It doesn't seem like it is reading it line by line, and it looks to only take the first line that I put in.
$ComputersPath = "C:\temp\kofaxcomputers.txt"
Get-Content $ComputersPath | ForEach {
if ($ComputersPath -ne $null) {
New-NetFirewallRule -DisplayName "Kofax - KTM" -Direction Inbound -RemoteAddress Any -Action Allow -Protocol TCP -LocalPort 2424
Write-Host "$_ installed" -ForegroundColor Green;
} else {
Write-Host "$_ failed" -ForegroundColor Red;
}}
If you are trying to create a firewall rule in a bunch of computers,
Have a list of computer in you text file(make sure there are no trailing spaces)
Read all the computers from the text file and save it in a variable.
Use Invoke-command to execute the New-NetFireWallRule on all those computers.
$Computers = get-Content -Path "C:\temp\kofaxcomputers.txt"
Invoke-Command -ComputerName $Computers -ScriptBlock {
New-NetFirewallRule -DisplayName "Kofax - KTM" -Direction Inbound -RemoteAddress Any -Action Allow -Protocol TCP -LocalPort 2424
}

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 Closing open sessions

I'm working on a large script where I run a Foreach loop, define variables in that loop and afterwards check if the $Server variable is pingable and if it is remotely accessible.
For this I use the following functions coming from the PowerShell help:
# Function to check if $Server is online
Function CanPing ($Server) {
$error.clear()
$tmp = Test-Connection $Server -ErrorAction SilentlyContinue
if ($?) {
Write-Host "Ping succeeded: $Server"; Return $true
}
else {
Write-Host "Ping failed: $Server."; Return $false
}
}
# Function to check if $Server is remotely accessible
Function CanRemote ($Server) {
$s = New-PSSession $Server -Authentication Credssp -Credential $Credentials -Name "Test" -ErrorAction SilentlyContinue
if ($s -is [System.Management.Automation.Runspaces.PSSession]) {
Enter-PSSession -Session $s
Exit-PSSession
Write-Host "Remote test succeeded: $Server."; Return $true
}
else {
Write-Host "Remote test failed: $Server."; Return $false
}
}
# Execute functions to check $Server
if ($Server -ne "UNC") {
if (CanPing $Server) {
if (-Not (CanRemote $Server)) {
Write-Host "Exit loop REMOTE" -ForegroundColor Yellow
continue
}
}
else {
Write-Host "Exit loop PING" -ForegroundColor Yellow
continue # 'continue' to the next object and don't execute the rest of the code, 'break' exits the foreach loop completely
}
}
Every time when I run this code, there is a process created on the remote server called wsmprovhost.exe. This process represents the PowerShell session, if the info I found on the web is correct. However, when doing Get-PSSession $Server there are no open sessions displayed in the PowerShell ISE, even though the processes are visible on the remote server and can only be killed with the Task Manager.
When I run this code often the limit of open sessions is reached because every time a new process wsmprovhost.exe is added to the $Server and the command errors out. I've tried to solve this by adding Exit-PSSessionto the code, but it doesn't close the session.
Any help or ideas are more than welcome.
The problem is that Enter-PSSession. Enter-PSSession can only be used interactively, you can't use it in a script. I'd suggest something more like this:
# Function to check if $Server is remotely accessible
Function CanRemote ($Server) {
Try {
$s = New-PSSession $Server -Authentication Credssp -Credential $Credentials -Name "Test" -ErrorAction Stop
Write-Host "Remote test succeeded: $Server."
$true
Remove-PSSession $s
}
Catch {
"Remote test failed: $Server."
$false
}
}
If I have understood correctly, Your remote ps-session are not getting closed.
To my understaning, Get-PSSession will show the session till your local session
is alive (I mean the session you created the remote ps-session) but once your local session
ends Get-PSSession will not show them cause they are no more live on your computer
rather on the remote system (or) they are no more in local session scope.
You can get the session using the command
Get-PSSession -ComputerName server_name
If you want to remove them you can do like
Get-PSSession -ComputerName server_name | Remove-PSSession
Even After executing the below command also, if you are not able to create session
Get-PSSession -ComputerName server_name | Remove-PSSession
Please, Restart the service Windows Remote Management (WS-Management) in the target machine.

Resources