Search code examples
windowspowershellnetwork-programmingp2pnetwork-connection

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:

  1. go to the properties of Ethernet adapter: Enter properties

  2. uncheck at "Sharing" section this check-box: un-check

  3. re-check these boxes (at the picture at step 4)

  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.


Solution

  • 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
    
    

    enter image description here

    enter image description here

    enter image description here