通过 powershell 进行 ICS

通过 powershell 进行 ICS

为了通过 powershell 启用 ICS,我使用了以下命令:

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

但遇到如下错误:

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

如何克服这种情况?

答案1

当它尝试在第 14 行使用它时,它会告诉您它$c是 Null(未定义)。

这导致$config无法填充(因此它保持未定义/空),从而导致第二和第三个错误。

要修复此问题,请确定为什么$c没有填充。

相关内容