46

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?

Hennes
  • 65,804
  • 7
  • 115
  • 169
utapyngo
  • 1,973
  • 2
  • 19
  • 33

7 Answers7

29

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.

utapyngo
  • 1,973
  • 2
  • 19
  • 33
9

I have created a simple command line tool for this.

  1. Download and unzip or git clone git@github.com:utapyngo/icsmanager.git

  2. Build by running build.cmd

  3. Register the HNetCfg COM library: regsvr32 hnetcfg.dll (it is a standard library located at %WINDIR%\System32)

Command-line usage

  1. Open the command line prompt as administrator

    cd to the icsmanager directory (or icsmanager-master if you downloaded zip).

  2. Type icsmanager

    This should display available network connections. Notice the GUID attribute. To use this tool you need to have at least two connections.

  3. Type icsmanager enable {GUID-OF-CONNECTION-TO-SHARE} {GUID-OF-HOME-CONNECTION}

    This should enable ICS.

Powershell usage

  1. Import module:

    Import-Module IcsManager.dll

  2. List network connections:

    Get-NetworkConnections

  3. Start Internet Connection Sharing:

    Enable-ICS "Connection to share" "Home connection"

  4. Stop Internet Connection Sharing:

    Disable-ICS


Disclaimer: I did not test the tool yet. Use it at your own risk. Feel free to open an issue at GitHub if something does not work. Pull requests are also welcome.

utapyngo
  • 1,973
  • 2
  • 19
  • 33
4

Here is another PowerShell command line utility in the form of a PowerShell module. I have written it partly based on code from this thread and I have tested and used it on a Windows 10 machine. It contains three simple functions to manage ICS and works with PowerShell version 3.0 and above.

Installing:

Download the PowerShell module file (.psm1) and copy it to your PSModulePath (usually C:\Users\%USERNAME%\Documents\WindowsPowerShell\Modules\<Module Folder>\<Module Files>. Name the <Module Folder> exactly as the .psm1 file (in this case PSInternetConnectionSharing) and PowerShell will automatically find the module and its functions. All functions must be run as administrator.

Usage examples:

Set-Ics Shares the internet connection of a network connection (called the public connection) with another network connection (called the private connection).

Set-Ics -PublicConnectionName Ethernet -PrivateConnectionName 'VM Host-Only Network'

Set-Ics Ethernet 'VM Host-Only Network'

Get-Ics lists ICS status for all network connections, or optionally for the specified connections.

Get status for all network connections:

Get-Ics

Get status for the specified network connections:

Get-Ics -ConnectionNames Ethernet, Ethernet2, 'VM Host-Only Network'

Get-Ics Ethernet, Ethernet2, 'VM Host-Only Network'

Disable-Ics

Disables ICS for all network connections:

Disable-Ics
loxia_01
  • 51
  • 5
4

By my understanding, routing capability was removed from Windows since Vista and is only available now in Windows Server.

The following trick can be found on the Internet to re-enable netsh routing, which you can try at your own risk. I suggest first the usual precautions, including creating a system restore point.

  1. Get IPMONTR.DLL and IPPROMON.DLL from 2003 or from XP
  2. Copy them to WINDOWS\SYSTEM32
  3. Run in Command Prompt (cmd) as administrator :

    netsh add helper ipmontr.dll
    netsh add helper ippromon.dll

You might also need to set the Routing and Remote Access Service to Automatic startup.

Reboot before trying anything.

harrymc
  • 498,455
2

Unfortunately there is no such cmd command for Windows 7 or more, so I used this Visual Basic function to get it done:

Private Function EnableDisableICS(ByVal sPublicConnectionName As String, ByVal sPrivateConnectionName As String, ByVal bEnable As Boolean)  
    Dim bFound As Boolean
    Dim oNetSharingManager, oConnectionCollection, oItem, EveryConnection, objNCProps
    oNetSharingManager = CreateObject("HNetCfg.HNetShare.1")
    oConnectionCollection = oNetSharingManager.EnumEveryConnection
    For Each oItem In oConnectionCollection
        EveryConnection = oNetSharingManager.INetSharingConfigurationForINetConnection(oItem)
        objNCProps = oNetSharingManager.NetConnectionProps(oItem)
        If objNCProps.name = sPrivateConnectionName Then
            bFound = True
            MsgBox("Starting Internet Sharing For: " & objNCProps.name)
            If bEnable Then
                EveryConnection.EnableSharing(1)
            Else
                EveryConnection.DisableSharing()
            End If
        End If
    Next
    oConnectionCollection = oNetSharingManager.EnumEveryConnection
    For Each oItem In oConnectionCollection
        EveryConnection = oNetSharingManager.INetSharingConfigurationForINetConnection(oItem)
        objNCProps = oNetSharingManager.NetConnectionProps(oItem)
        If objNCProps.name = sPublicConnectionName Then
            bFound = True
            MsgBox("Internet Sharing Success For: " & objNCProps.name)
            If bEnable Then
                EveryConnection.EnableSharing(0)
            Else
                EveryConnection.DisableSharing()
            End If
        End If
    Next
    Return Nothing 'bEnable & bFound
End Function  

Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
    EnableDisableICS("YOUR ACTIVE NETWORK", "YOUR ADAPTOR TO SHARE", True)
End Sub

Please note that """" is required. Have fun.

karel
  • 13,706
1

The following should work

netsh routing ip autodhcp install
netsh routing ip autodhcp set interface name="Local Area Connection(or whereever your internet connection is from)" mode=enable
netsh routing ip autodhcp set global 192.168.0.1 255.255.255.0 11520
Craig
  • 19
1

Based on what I have read, if those that have posted said netsh doesn't work starting at 7 and up- that is incorrect. Now if it's strictly about "netsh routing", I guess you could be right, but this does work- I am about to show the contents of a batch file I have created that works on Windows 8.1. Instead of getting the usual comments and pieces of information, I am going to try and help those with the full information.

First, you need to make sure the connection you will be sharing is set to actually share the connection. This link here should get you going for that:

Set up a shared Internet connection using ICS (Internet Connection Sharing) at Windows Help.

  1. Open Network Connections by clicking the Start button, and then clicking Control Panel. In the search box, type adapter, and then, under Network and Sharing Center, click View network connections.

  2. Right-click the connection that you want to share, and then click Properties. If you're prompted for an administrator password or confirmation, type the password or provide confirmation.

  3. Click the Sharing tab, and then select the Allow other network users to connect through this computer’s Internet connection check box.

After you've followed the steps above to set up ICS on the host computer, make the following changes on all of the other computers (but not on the host computer).

  1. Open Internet Options by clicking the Start button, clicking Control Panel, clicking Network and Internet, and then clicking Internet Options.

  2. Click the Connections tab, and then click Never dial a connection.

  3. Click LAN Settings.

  4. In the Local Area Network (LAN) Settings dialog box, Under Automatic configuration, clear the Automatically detect settings and Use automatic configuration script check boxes.

  5. Under Proxy server, clear the Use a proxy server for your LAN check box, and then click OK.

Similar instructions are also available here.

To my knowledge, I think this should work for both Windows 7 and 8.

Now since the topic was about a command line solution, this is the batch file contents of how I get a virtual wireless adapter configured and ready to go.

Once it's created, you may have to use the instructions above and make sure you are sharing the source connection with the newly created virtual adapter that will be seen by your wireless devices.

Connection sharing .bat file:

@echo off
set _my_datetime=%date%_%time%
set _my_datetime=%_my_datetime: =_%
set _my_datetime=%_my_datetime::=%
set _my_datetime=%_my_datetime:/=_%
set _my_datetime=%_my_datetime:.=_%

cd\
    if NOT EXIST "C:\TEMP\switch.txt" (
        GOTO :START
    ) ELSE (
        GOTO :STOP
    )

:START
REM Create Temp File for On and Off switch.
ECHO WOOHOO >"C:\TEMP\switch.txt"

REM -- Output everything that is happening into a file called wifi.txt.
REM -- Start out with a timestamp at the top to show when it was done.
REM -- All 'netsh' commands are for setting up the SSID and starting the    sharing.
REM -- I stop and start when starting the service just for prosperity.

echo _%_my_datetime% >"C:\TEMP\wifi.txt"
netsh wlan set hostednetwork mode=allow ssid=ITWORKS key=111222333 >>    "C:\TEMP\wifi.txt"
netsh wlan stop hostednetwork >>"C:\TEMP\wifi.txt"
netsh wlan start hostednetwork >>"C:\TEMP\wifi.txt"
echo MSGBOX "Wifi Sharing Started!" > %temp%\TEMPmessage.vbs
call %temp%\TEMPmessage.vbs
del %temp%\TEMPmessage.vbs /f /q
GOTO :END


REM -- This will turn ICS off and give a prompt via VBS that you're turned off.
REM -- I timestamp when the service is turned off in the output file.
REM -- I delete the switch file to let the code know to turn it on when
REM -- when fired off again.  Tempmessage is the msgbox used to show the service
REM -- has been turned off.  Same for the msgbox above when it's on.

:STOP
echo OFF AT _%_my_datetime% >>"C:\TEMP\wifi.txt"
netsh wlan stop hostednetwork >>"C:\TEMP\wifi.txt"
DEL /Q "C:\TEMP\switch.txt"
echo MSGBOX "Wifi Sharing Stopped!" > %temp%\TEMPmessage.vbs
call %temp%\TEMPmessage.vbs
del %temp%\TEMPmessage.vbs /f /q

:END

I'll be more than happy to answer questions about this because there is going to be some unique situations and I'd like to help since I had to piece together what I found above.

But to bring this to perspective, this works on Windows 8.1 using an Ethernet connection into a laptop sharing its connection to the virtual adapter. It may work just as well if you are trying to share a source Wireless connection.