43

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?

5
  • 4
    Can't try this just now, but you might want to try running Process Monitor and pointing it at your Registry. See what keys/values change when you toggle & apply the setting, then write your script accordingly.
    – Iszi
    Sep 17, 2012 at 20:12
  • Related question/info over on StackOverflow: Enable Internet Connection Sharing programmatically Mar 17, 2013 at 17:35
  • The Microsoft-Windows-SharedAccess Unattended Windows Setup component is so close, but it only works at Windows Setup! technet.microsoft.com/en-us/library/ff715511.aspx Sep 20, 2013 at 20:26
  • 2
    @SmartManoj, it is an option too, but please convert your comment to an answer and copy the script here. A link can become outdated.
    – utapyngo
    Jan 23, 2020 at 4:47
  • That link doesn't even work. Also, Python on Windows, seriosly? Jan 28, 2020 at 20:01

7 Answers 7

26
+50

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.

9
  • 1
    Ooh, I didn't know you could do COM interop with PowerShell! I assume you need some [System.Runtime.Interopservices.Marshal]::ReleaseComObject(...) sprinkled in. Sep 23, 2013 at 16:19
  • The call to EnableSharing is throwing this exception, even though I'm running PowerShell as Administrator:Exception: Exception calling "EnableSharing" with "1" argument(s): "An event was unable to invoke any of the subscribers (Exception from HRESULT: 0x80040201)" --> Exception has been thrown by the target of an invocation. --> An event was unable to invoke any of the subscribers (Exception from HRESULT: 0x80040201) Sep 23, 2013 at 20:36
  • Try running regsvr32 hnetcfg.dll as administrator manually.
    – utapyngo
    Sep 24, 2013 at 2:19
  • 5
    In newer versions of Powershell, .SharingType is now .SharingConnectionType
    – Baodad
    Dec 28, 2013 at 18:15
  • 1
    @utapyngo, the same error on Windows 10, An event was unable to invoke any of the subscribers (Exception from HRESULT: 0x80040201).
    – Suncatcher
    Mar 7, 2017 at 20:58
9

I have created a simple command line tool for this.

  1. Download and unzip or git clone [email protected]: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.

12
  • Neat. This uses an external binary called NETCONLib; where did it come from? What does it do? Sep 23, 2013 at 15:09
  • Aha. This is a COM class wrapper for the "NetCon 1.0 Type Library" included with Windows. Sep 23, 2013 at 15:18
  • @JacobKrall, yes, it is located at C:\Windows\System32\hnetcfg.dll.
    – utapyngo
    Sep 23, 2013 at 15:53
  • This looks like it will do exactly what I want - I will try it out. Sep 23, 2013 at 16:13
  • 1
    Sorry, I did it several months ago and forgot that HNetCfg should be registered manually with regsvr32 hnetcfg.dll. And I learnt about hnetcfg.dll at msdn.microsoft.com/en-us/library/windows/desktop/…
    – utapyngo
    Sep 24, 2013 at 14:16
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.

7
  • 1
    Is it legal to copy files from XP if I don't have XP license?
    – utapyngo
    Sep 24, 2013 at 13:22
  • 1
    Tried this on Windows 7 64bit. Copied the files from XP 64 bit. Running as administrator. Errors: The following helper DLL cannot be loaded: IPMONTR.DLL. The following helper DLL cannot be loaded: IPPROMON.DLL.
    – utapyngo
    Sep 24, 2013 at 14:14
  • 1
    I tried it too the "add helper" and I am sorry to confirm that it doesn't work for 64-bit. As regarding the legality of transplanting dlls to which you have right on both OSs, this is unclear. You don't have the right to modify Windows files, but copying them is maybe not ruled against in the XP license (it would astound me that Microsoft could have foreseen this in advance).
    – harrymc
    Sep 24, 2013 at 18:30
  • 1
    It should be mentioned in the answer that it does not work for 64-bit Windows. Please also mention that the files should be copied from XP 32-bit.
    – utapyngo
    Sep 25, 2013 at 1:35
  • @utapyngo: One cannot be sure that there is really is no way to make this work on 64-bit. According to my studies, the problem is that more dlls than these two should be copied, but analyzing fully the problem requires more time than I can give.
    – harrymc
    Sep 25, 2013 at 5:47
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
2
  • 1
    Awesome! Works well on Windows 10. I had to do set-executionpolicy remotesigned before module usage (I was getting PSInternetConnectionSharing.psm1 cannot be loaded because running scripts is disabled on this system). Now I can share my Windows-only Check Point VPN to my Linux machine.
    – estibordo
    Apr 20, 2021 at 17:47
  • 1
    @estibordo I'll make a note of set-executionpolicy in ReadMe.
    – loxia_01
    Apr 22, 2021 at 15:42
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.

0
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
1
  • 8
    It was possible to do with netsh routing in Windows XP but in Windows 7 they have removed that command. That's why I'm only asking about Windows 7.
    – utapyngo
    Jan 3, 2013 at 4:54
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.

7
  • Welcome to Super User! Thanks for the detailed answer, I have edited to your question to streamline some of the text and to put your bat file contents in a code block. You can see other formatting instructions if there are any problems with it- please check to make sure I haven't altered the meaning of the code.
    – bertieb
    Aug 2, 2015 at 18:43
  • Yeah that's fine and thanks. I knew I should have done a better job on the formatting. Nice touch on the MS link to prevent from having to actually go there. Aug 3, 2015 at 19:05
  • Don't worry about it, you'll pick up the markdown syntax quickly enough :) Including the link content is part of a policy here on answering questions - links can go stale, change or disappear. This is less likely in the case of Microsoft, but still very possible. It is good practice to put everything necessary for a solution in the answer itself. Look forward to seeing more good answers from you!
    – bertieb
    Aug 3, 2015 at 20:42
  • In 1st numbered list one have to select the source of the Internet Jan 20, 2020 at 1:48
  • Sorry, but this is completely off-topic. In this answer ICS controlled manually via GUI, the rest of the text is basically well-known netsh wlan hostednetwork commands with common misconceptions. Jan 28, 2020 at 20:38

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .