I was just asked on Twitter to write a script to disable all disconnected NIC’s on Windows Server 2008 R2 through the use of PowerShell.
First, let’s start with the basics… getting all NIC’s. For this you can use WMI:
Get-WmiObject Win32_NetworkAdapter –ComputerName localhost
Now, we only want to get the NIC’s that are disabled. You can do this by filtering on the NetConnectionStatus with a specific value… where disconnected has the value of 7 (and connected has a value of 2 ).
Get-WmiObject Win32_NetworkAdapter –ComputerName localhost -Filter ‘NetConnectionStatus = 7’
Alright… now that we’ve got the NIC’s we want to disable them… when you do a little | Get-Member after the command you’ll get all possible properties, script properties… and methods One of those methods is “disable”
So, now we have a choice to make… do we want to use variables or jam it all op into one line?
When using variables, the following will accomplish our goal:
$NIC = Get-WmiObject Win32_NetworkAdapter –ComputerName localhost -Filter ‘NetConnectionStatus = 7’
And when we want to do it with a single line of code:
(Get-WmiObject Win32_NetworkAdapter -ComputerName LocalHost -Filter ‘NetConnectionStatus = 7’).Disable()
Now, as I mentioned before you can get the available methods by using get-member after a command… A few of the other methods are Enable and Reset You can handle them the same way as you’ve just used the Disable method… So what if you would want to enable a specific NICs, for example one with “Wireless” in the name?…
To find the wireless NIC’s:
Get-WmiObject Win32_NetworkAdapter –ComputerName localhost -Filter "Name LIKE ‘%Wireless%’"
And to enable the wireless NIC’s:
$NIC = Get-WmiObject Win32_NetworkAdapter –ComputerName localhost -Filter "Name LIKE ‘%Wireless%’"
Or when you want to do it in one line:
(Get-WmiObject Win32_NetworkAdapter -ComputerName LocalHost -Filter "Name LIKE ‘%Wireless%’").Enable()
And what if you want to reset all your NIC’s? When using a variable:
$NIC= Get-WmiObject Win32_NetworkAdapter –ComputerName localhost
And in one line:
(Get-WmiObject win32_networkadapter -computerName LocalHost).Reset()