通过MSFT_NetAdapter启用/禁用网络适配器

时间:2015-05-25 07:48:31

标签: c++ c#-4.0 vbscript wmi wmi-query

我尝试在OS Windows 8中通过MSFT_NetAdapter禁用/启用网络适配器。

strComputer = "."

Set objWMIService = GetObject("winmgmts:{impersonationLevel=Delegate," _
        & "authenticationLevel=pktPrivacy}\root\standardcimv2")

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

例如,仅使用“禁用”。 MSFT_NetAdapter返回" DeviceID"或"名称",当您调用方法objOperatingSystem.Disable时会收到错误0x80041003"当前用户无权执行操作"。 我尝试使用此代码:

strComputer = "."

Set objWMIService = GetObject("winmgmts:{impersonationLevel=Delegate," _
        & "authenticationLevel=pktPrivacy}\root\cimv2")

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上正常工作。网络适配器在代码后立即切换。在OS窗口8中禁用/启用需要在代码后重新启动系统。 如何在OS Windows 8中管理网络适配器?

1 个答案:

答案 0 :(得分:3)

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

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

            //
            //  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)
            {
            }