ICS through powershell

0

In order to enable ICS through powershell, I used the following:

# 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() 

but encountering errors like:

Exception calling "Invoke" with "1" argument(s): "Cannot process argument because the value of argument "arguments" is
null. Change the value of argument "arguments" to a non-null value."
At C:\a.ps1:14 char:62
+ $config = $m.INetSharingConfigurationForINetConnection.Invoke <<<< ($c)
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

You cannot call a method on a null-valued expression.
At C:\a.ps1:25 char:22
+ $config.EnableSharing <<<< (0)
    + CategoryInfo          : InvalidOperation: (EnableSharing:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

You cannot call a method on a null-valued expression.
At C:\a.ps1:28 char:23
+ $config.DisableSharing <<<< ()
    + CategoryInfo          : InvalidOperation: (DisableSharing:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

How to overcome this situation?

anmol sharma

Posted 2015-12-24T19:19:37.367

Reputation: 1

Answers

0

It's telling you $c is Null (not defined) when it tries to use it on line 14.

This is causing $config to not get populated (so it remains undefined/null), leading to the second and third errors.

To fix it, determine why $c isn't getting populated.

Ƭᴇcʜιᴇ007

Posted 2015-12-24T19:19:37.367

Reputation: 103 763

NetConnectionProps.Invoke($_).Name -eq "Ethernet" is what $c is holding. Actually, the PC is connected to WLAN, and not Ethernet. Is this the issue??? – anmol sharma – 2015-12-25T06:55:01.600

That could be the issue. Try putting a breakpoint on the $c = $m.EnumEveryConnection |? { $m.NetConnectionProps.Invoke($_).Name -eq "Ethernet" } line, and print the output of $C to the console to check if it's correctly filled. – Smeerpijp – 2015-12-28T10:56:17.943