Powershell in win 10: System.AccessViolationException on enabling ICS

Win10 they broke many things - VPN reconnect, ICS sharing etc, I was trying to schedule a script to fix those (VPN reconnect was a success) - but the one I found for ICS - powershell script to turn off and turn back on ICS (that fixes the sharing stopping working in Win10 after internet reconnect) crashes on line where it enables sharing for public adapter with error `System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt. at IDispatchInvoke`, even thought checkboxes in adapter seem to go off and back on - internet sharing doesn’t start working back - no wonder, cuz powrshell crashes in that moment.

screenshot - https://i.stack.imgur.com/zcv4i.jpg


    # Constants
    $public = 0
    $private = 1
    Write-Host "Creating netshare object..."
    $netshare = New-Object -ComObject HNetCfg.HNetShare
    Write-Host "Getting public adapter..."
    $publicadapter = $netshare.EnumEveryConnection | Where-Object {
        $netshare.NetConnectionProps($_).Name -eq "MYISP_VPN"
    Write-Host "Getting private adapter..."
    $privateadapter = $netshare.EnumEveryConnection | Where-Object {
        $netshare.NetConnectionProps($_).Name -eq "Home_local"
    Write-Host "Disabling sharing for adapters...."
    Start-Sleep -s 3
    Write-Host "Enabling sharing for private adapter...."
    Write-Host "Enabling sharing for public adapter...."
    # Clean up
    Remove-Variable netshare


We don’t use square brackets for code formatting; use angle brackets as indicated above the posting textbook.

My experience with ICS is that it has a lot of moving parts in terms of getting it enabled. Anytime I’ve tried to script it, it’s worked sometimes, but not always, and when it fails it’s with weird errors. Yours almost makes me wonder if it’s a networking device driver getting involved somehow. Short answer, I’ve personally not had a lot of love making this happen via script.

Part of the problem is that you’re basically using PowerShell to write C# code that uses Interop to talk to an old-ass COM object. It’s not exactly set up to succeed. I assume you’ve done the obvious and tried to lengthen your sleep time - have you tried running a script that JUST disables, and then running a script that JUST enables? I’m curious as to whether dropping and re-instantating the COM object would have any effect.

Yes, I’ve tried running line by line, and just separate lines, line that enables public adapter gives memory error, rest work fine