Windows – How to enable Internet Connection Sharing using command line

internet connectionpowershellwindows 7

I can do it manually by right-clicking on a network connection, opening the Sharing tab and clicking on the "Allow other network users to connect through this computer's Internet connection" check box.

Now I need to automate this task. Is there a command-line tool or a Powershell cmdlet to accomplish this?

Best Answer

Here is a pure PowerShell solution (should be run with administrative privileges):

# 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 "Ethernet" }

# 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

# Enable sharing (0 - public, 1 - private)
$config.EnableSharing(0)

# Disable sharing
$config.DisableSharing()

See also this question at social.msdn.microsoft.com:

You have to enable the public interface on the adapter you are connecting to and enable sharing on the private interface for the adapter you want to be able to use for the network.

Related Question