PowerShell script to check if host NICs are enabled/disabled and enable them

As a part of a larger script I needed to check if a host’s NICs were enabled or disabled and enable them if needed. After a while, I was able to get it going. Here it is:

Clear-Host
Write "Checking adpater status and enabling if any disabled"

$DisabledAdapters = Get-NetAdapter | where {$_.Status -eq "Disabled"} | select -ExpandProperty Name
if ($DisabledAdapters -notlike "Disabled")
{Enable-NetAdapter -Name $DisabledAdapters
Write "Enabling disabled NICs"
}else {Write "All NICs already enabled"}
Pause

The bits that got me initially were:

  • The getadapter command would spit out a whole line of output but I wanted just the state of the adapter (disabled state that is). -expandproperty to the rescue. It let me use the actual name of the adapter which in turn was what was needed by the enable-netadapter cmdlet
  • The if command to check whether the adapter(s) was disabled needed the -notlike operator. The variable $DisabledAdapters stored the name of the adapter and -notlike checked if it was actually set to “Disabled”. -ne would not work
  • Finally, there’s a bug in the if/else statement that bit me, you can read about it here. The script above is free of this bug

Hope this script helps someone!

Leave a Comment

Your email address will not be published.