Configure Internet Connection Sharing with PowerShell

My test environment runs as Hyper-V VM’s on my IBM Thinkpad P50. I use ICS (Internet Connection Sharing) to shield my Hyper-V test environment virtual network from my production network connection. ICS allows me to temporarily give my test VM’s Internet access when needed without putting them directly on the production network. You might ask why? Because my test environment VM’s run things like DHCP servers that would cause havoc on the production network. I use an Internal virtual switch with Hyper-V and I keep both that internal network adapter and ICS disabled unless I need the VM’s to have Internet access.

From what I’ve found, there’s no easy way to configure ICS with PowerShell so I decided to write a couple of functions to accomplish that task. The first function, Get-MrInternetConnectionSharing retrieves the current settings.

Since the function used to retrieve the information can accept more than one network adapter name, I didn’t want to use parameter validation to verify the name otherwise the function would terminate for all the ones specified if any invalid names were specified. I decided to handle any invalid network adapter names in the code itself with a try/catch block and a continue statement which skips producing any output for the invalid ones other than the warning message that I have it generate with Write-Warning.

I’ll specify the two network adapters used in my Internet connection scenario.

The second function, Set-MrInternetConnectionSharing configures the settings.

I’ve handled all of the problems that I ran into when testing this function. The specified network adapters have to exist as well as be enabled in order to be configured otherwise an error is generated. Both of those problems are handled early on with input validation via ValidateScript since there’s no need to allow the function to even get started unless those requirements are met.

Next, I ran into a scenario where ICS was disabled for the Internet connection network adapter, but was enabled for the Internal one which generated an error. I’ve handled that problem first thing in the Begin block by checking to make sure ICS is disabled before attempting to continue.

Now I’ll configure the network adapter named Ethernet to share its Internet connection with the one named Internal Virtual Switch.

You can see that Internet connection is enabled by checking the settings again.

The functions shown in this blog article can be downloaded as part of my MrToolkit module from my PowerShell repository on GitHub.

µ

Leave a Reply

%d bloggers like this: