构建一个脚本来选中/取消选中以太网适配器上的共享框

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

我们在主机和一些目标之间建立了 P2P 连接, 由于稳定性问题,连接有时会死掉,我们需要取消选中“允许其他网络用户通过这台计算机的互联网连接进行连接”,添加“家庭网络连接:”作为“p2p”,同时取消选中“允许其他网络”用户控制或禁用共享 Internet 连接”以解决连接问题。

我们不想试图找到根本原因,我们决定建立这个解决方案。

以下是我要构建 PS 脚本的步骤:

  1. 进入以太网适配器的属性: Enter properties

  2. 在“共享”部分取消选中此复选框: un-check

  3. 重新选中这些框(在第 4 步的图片处)

  4. 添加到“家庭网络连接”p2p“。 re-check

我试图构建一个脚本来执行此操作,但是,它破坏了我的主机,我们不得不在尝试 运行 之后重新构建主机,请不要 运行它在您的计算机上:

echo Stability tool...
# High Privilage level script: 

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

我更喜欢 PS 脚本,但如果有另一种方法可以自动执行 tyhat - 我会很高兴听到。

在使用 NeoTheNerd 的答案后,这里是我用来构建一个批处理文件的代码,它执行我要求的刷新('p2p' 的一个适配器以禁用共享和 'Ethernet' 适配器完成与家庭网络连接到 'p2p' 适配器的分片) - 在这里我将给出一个完整的描述来构建 4 个文件一起进行刷新(文件的复制和移动在这个项目中是必不可少的,因为我从服务器下载它们,这里我把它们放在本地位置):

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

文件夹位置:c:\scripts_for_power_shell\Shell_Functions

三个文件的内容如下: 获取 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
            }

        }

    }

}

设置-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 ''

所以 4 个文件(包含三个 ps1 文件的批处理),双击批处理文件后,为 P2P 连接建立完全刷新。

非常感谢 NeoTheNerd、Kiran 和 Bluuf 的帮助。

要有建设性地使用脚本的大杂烩,而不对每个单独的脚本应用逻辑是不合逻辑的。

如果您查看此网页 - 使用 PowerShell 配置 Internet 连接共享

https://mikefrobbins.com/2017/10/19/configure-internet-connection-sharing-with-powershell/

它走出了你所寻求的。

步骤 1 使用函数 Get-MrInternetConnectionSharing 检索当前设置

步骤 2 使用 Get-MrInternetConnectionSharing 函数指定我的 Internet 连接中使用的网络适配器。

#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

步骤 3

使用第二个函数,Set-MrInternetConnectionSharing配置设置


#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