通过MSFT_NetAdapter使能/禁用网卡

Enable/Disable of the network adapter through MSFT_NetAdapter

本文关键字:网卡 使能 MSFT NetAdapter 通过      更新时间:2023-10-16

我正在尝试在Windows 8操作系统中通过MSFT_NetAdapter禁用/启用网络适配器。

strComputer = "."
Set objWMIService = GetObject("winmgmts:{impersonationLevel=Delegate," _
        & "authenticationLevel=pktPrivacy}rootstandardcimv2")
Set colSettings = objWMIService.ExecQuery("Select * from MSFT_NetAdapter")
For Each objOperatingSystem in colSettings 
    Wscript.Echo _ 
    "DeviceID: " & objOperatingSystem.DeviceID & vbCrLf & _
    "Name: " & objOperatingSystem.Name
objOperatingSystem.Disable
Next

例如只使用Disable。MSFT_NetAdapter返回"DeviceID"或"Name",当你调用objOperatingSystem方法时。禁用获取错误0x80041003 "当前用户没有执行操作的权限"。我试着用这个代码:

strComputer = "."
Set objWMIService = GetObject("winmgmts:{impersonationLevel=Delegate," _
        & "authenticationLevel=pktPrivacy}rootcimv2")
Set colSettings = objWMIService.ExecQuery("Select * from Win32_NetworkAdapter where PhysicalAdapter = true")
For Each objOperatingSystem in colSettings 
    Wscript.Echo _ 
    "DeviceID: " & objOperatingSystem.DeviceID & vbCrLf & _
    "Name: " & objOperatingSystem.Name
    objOperatingSystem.Disable
Next

此代码在windows 7上运行良好。执行完代码后,立即切换网络适配器。在windows 8操作系统中,禁用/启用需要在代码后重新启动系统。windows 8操作系统下如何管理网卡

您需要以管理员权限运行。如果您的应用程序将由没有管理员权限的用户运行,那么您可以安装与您的应用程序通信的服务。

此代码禁用所有网络适配器。

            //
            //  In Windows Vista this can be accomplished through a simple WMI query.
            //
            try
            {
                using (var query = new ManagementObjectSearcher("select * from Win32_NetworkAdapter where NetConnectionStatus = 2"))
                {
                    using (var devices = query.Get())
                    {
                        foreach (ManagementObject device in devices)
                        {
                            try
                            {
                                device.InvokeMethod("Disable", null);
                            }
                            catch (Exception ex)
                            {
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
            }